I am writing an Angular 4 app. This contains 2 lists. If I click an element in the first list the result should be a subset of my second list (via foreign keys) in a new view. I do the filtering by id (foreign key) with a function in my service. In my component I receive just 'undefined'. I think, the reason is that I use an Observable in my service and the data is not ready, when the new view for the subset list is shown. How can I do this in another way to reach my goal?
calling the method in my service via click event in a mat-table-cell:
method in my service.ts
getItemsByID(id: number): Observable<Item[]> {
return this.http.get('/api/Item').map((response) => {
console.log(id); //shows correct item id
console.log(this.items.filter(iteration => item.item_id === id)); // shows correct array of subset list
return this.items.filter(item=> item.item_id === id);
});
}
method in my component.ts
getItem(): void {
const id = +this.route.snapshot.paramMap.get('id');
this.itemService.getItemsByID(id)
.subscribe(response => this.items = response);
console.log(this.items); // shows 'undefined'
}
What else do I need to show you from my code?
Complete log:
undefined
4
Array [ {…}, {…}, {…}, {…} ]
Thanks a lot!
I infer you're using the HttpClient as http, given response as returned a list and .json() is not a function, as you wrote.
So, it's better if you remove the this.items property on your service. Perhaps you think that this property exist as this.items in both service and component? this points to separate objects. And would be best if service didn't had to maintain a state like this one, but only methods.
getItemsByID(id: number): Observable<Item[]> {
return this.http.get<Item[]>('/api/Item').map((items) => {
console.log(id); //shows correct item id
const filtered = items.filter(item => item.item_id === id);
console.log(filtered); // shows correct array of subset list
return filtered;
});
}
Then consume the service:
getItem(): void {
const id = +this.route.snapshot.paramMap.get('id');
this.itemService.getItemsByID(id)
.subscribe(items => {
this.items = items;
console.log(items);
);
});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With