Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get data from service based from id?

I dont know how to get data from service based on id in route on angular and need some help

this is my account.service.ts

import { Observable } from "rxjs";

export class AccountsService {
  
  
    accounts = [
        {
          id: 1,
          name: 'Master Account',
          age: 23,
          status: 'active'
        },
        {
          id: 2,
          name: 'Testaccount',
          age: 23,
          status: 'inactive'
        },
        {
          id: 3,
          name: 'Hidden Account',
          age: 23,
          status: 'unknown'
        }
      ];
      
  }

      
      getData(id: string) {
        
      }
}

This is my component, in this part I can get the id but I don’t know to get data from array in service based this id

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { AccountsService } from 'src/app/account.service';

@Component({
  selector: 'app-detail-card',
  templateUrl: './detail-card.component.html',
  styleUrls: ['./detail-card.component.css']
})
export class DetailCardComponent implements OnInit {

  constructor(
    private route:ActivatedRoute,
    private accountService:AccountsService
  ) { }

  ngOnInit(): void {
    this.getData()
  }

  getData(){
    const cardId = this.route.snapshot.paramMap.get('id');
  }

}

>Solution :

In you service

  getData(id: string) {
    return this.accounts.find(x=> x.id == id)
  }

and in your component :

getData(){
const cardId = this.route.snapshot.paramMap.get('id');
const account = this.accountService.getData(cardId)
 console.log(account)
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading