Before starting: I know this is quite a lengthy post compared to others, but the problem is at quite a beginner level. My gut feeling tells me that something is going on with the method in the service and how I am using the .filter
to get a certain object from the array. I've also tried with .find
but with no luck.
I've tried making a new component which, if called by the path app-notedetails/:id
returns the Note object only containing the specified id. Instead, it returns all of the note objects and on the UI it shows that all of them have, for example, id 1 (if I put the parameter 1). I've really been battling with it but couldn't figure out what could possibly gone wrong.
These notes are created in note.service.ts and put in an array.
notes: Note[] = [
{
id: "1",
title: "First note",
description: "This is the description for the first note",
categoryId: "1"
},
{
id: "2",
title: "Second note",
description: "This is the description for the second note",
categoryId: "1"
}
];
Inside this service, there is a method called getNoteByID
.
getNoteByID(id:any): Note[] {
let note = this.notes.filter(el => el.id = id);
return note;
}
The id is taken from notedetails.component.ts where the parameter from the url is taken and passed to the method inside the service on initialization.
export class NotedetailsComponent implements OnInit {
notes: Note[];
id: number;
sub: any;
constructor(private noteService: NoteService, private route: ActivatedRoute) {
}
ngOnInit(): void {
this.sub = this.route.params.subscribe(params => {
this.id = +params['id'];
});
this.notes = this.noteService.getNoteByID(this.id);
}
}
And then the HTML is this:
<div *ngFor ='let note of notes'>
<p>Id: {{note.id}}</p>
<p>Title: {{note.title}}</p>
<p>Description: {{note.description}}</p>
<p>Category Id: {{note.categoryId}}</p>
</div>
Therefore, why is it returning all notes and why is it assigning them the same ID? (you can see the result here: https://imgur.com/K7BHfHX)
question from:
https://stackoverflow.com/questions/65921781/component-path-containing-parameter-returns-all-objects-instead-of-just-one 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…