Reputation: 113
I am learning Angular and I ran into a problem today. I am displaying an array of JS objects and when I click on a single item, I want a new component to display only the details of that object. I am using a service to hold and do CRUD operations in the array. Below is the code for getServer which finds a single object in the array by id.
getServer(id: number) {
const server = this.servers.find(
(s) => {
return s.id === id;
}
);
return server;
}
The problem shows up when I click on a single object. The above method is returning an "undefined" object. I tried placing breakpoints in the code and found that even after reaching the return statement with the correct object, the code again goes back to the find method and runs the arrow function and then returns undefined. Find the screenshots when I clicked the first object (id:1) below:
getServer is called in another component (ServerComponent).
ngOnInit() {
const id = +this.activatedRoute.snapshot.params["id"];
this.server = this.serversService.getServer(id);
this.activatedRoute.params.subscribe(
(params:Params)=>{
this.server = this.serversService.getServer(params["id"]);
}
);
}
Stackblitz link: https://routing-start.stackblitz.io
Upvotes: 0
Views: 660
Reputation: 1458
getServer method is called by 2 things as commented
ngOnInit() {
const id = +this.activatedRoute.snapshot.params["id"];
this.server = this.serversService.getServer(id); // Here with id as number
this.activatedRoute.params.subscribe(
(params:Params)=>{
this.server = this.serversService.getServer(params["id"]); // Here with id as string
}
);
}
and in your
getServer(id: number) {
const server = this.servers.find(
(s) => {
return s.id === id;
}
);
return server;
}
you are doing a type strict check with ===
and thats the reason it is not able to find. You can replace ===
with ==
or call method with proper argument as below
this.server = this.serversService.getServer(+params["id"])
Upvotes: 1