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
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)
}