I use Angular5 with httpClient to request a rest api. My issue is I perfectly get lists of objects but I can't obtain a single object. I use modules for this module I have a service in which I have my call to the api-rest:
getUser(id: string) {
return this.http.get<IUserComponent>('apiAddress/getbyid?id=' + id);
}
In the component I call it
ngOnInit() {
this.id = this.route.snapshot.paramMap.get('id');
this.getUser(this.id);
}
getUser(id): void {
this.userService.getUser(id).subscribe(data => {
this.user = data;
});
}
And I call user in my template:
<p>
{{user.name}}
</p>
When I do that I get nothing displayed and the error
TypeError: _co.user is undefined
ERROR CONTEXT Object { view: Object, nodeIndex: 12, nodeDef: Object, elDef: Object, elView: Object }
I can get something displayed but I still get the error if in the service I say I want an array
getUser(id: string) {
return this.http.get<IUserComponent[]>('apiAddress/getbyid?id=' + id);
}
and when I call it I say
ngOnInit() {
this.id = this.route.snapshot.paramMap.get('id');
this.getUser(this.id);
}
getUser(id): void {
this.userService.getUser(id).subscribe(data => {
this.user = data[0];
});
}
And finally if I call the service:
getUser(id: string) {
return this.http.get<IUserComponent[]>('apiAddress/getbyid?id=' + id);
}
and call it
ngOnInit() {
this.id = this.route.snapshot.paramMap.get('id');
this.getUser(this.id);
}
getUser(id): void {
this.userService.getUser(id).subscribe(data => {
this.users = data;
});
}
I can display the data with *ngFor and don't get any error. I don't very understand why.
In the hero tutorial of Angular https://angular.io/tutorial/toh-pt6 They wrote this service to get all:
getHeroes (): Observable<Hero[]> {
return this.http.get<Hero[]>(this.heroesUrl)
.pipe(
tap(heroes => this.log(`fetched heroes`)),
catchError(this.handleError('getHeroes', []))
);
}
and this one to get a single one
getHero(id: number): Observable<Hero> {
const url = `${this.heroesUrl}/${id}`;
return this.http.get<Hero>(url).pipe(
tap(_ => this.log(`fetched hero id=${id}`)),
catchError(this.handleError<Hero>(`getHero id=${id}`))
);
}
where the pipe is used to do several action so here tap and cathError and tap I am not sure to understand correctly what it is used for there is a doc https://github.com/ReactiveX/rxjs/blob/5.5.2/src/operators/tap.ts#L14 but it seems to be used for debug.