I apologize first of all for my English which is not good at all. I am asking for your help today, because I am having an incomprehensible problem!
I'm currently on Angular and using .subscribe to track my obsersables. Here is my component:
export class SiteDetailComponent implements OnInit {
public test1 : ISite = <ISite>{};
public test2: ISite[] = [];
public errMsg : string = "";
constructor(...)
ngOnInit() {
const id : number = Number(this.route.snapshot.paramMap.get('id'));
this.SiteListeService.getSiteById(id).subscribe({
next: site => {
this.test1 = site;
},
error: err => this.errMsg = err
});
this.SiteListeService.getSites().subscribe({
next: sites => {
this.test2 = sites;
},
error: err => this.errMsg = err
});
As you can see I made a .subscribe on 2 Observable: this;SiteListeService.getSites() and this.SiteListeService.getSiteById(id), here is the service concerned (which I have imported the constructor).
public getSites(): Observable<ISite[]> {
return this.http.get<ISite[]>(this.HOTEL_API_URL + "test/").pipe(
tap(test2 => console.log('test2 : ', test2)),
catchError(this.handleError)
);
}
public getSiteById(id : number): Observable<ISite> {
return this.http.get<ISite>(this.HOTEL_API_URL + "test/" + id).pipe(
tap(test1 => console.log('test1 : ', test1)),
catchError(this.handleError)
);
}
The problem being that the test1 variable that I use in my .html does not want to be displayed, here is the example:
<h5 class="card-title">{{ test1.nom }} </h5>
On the other hand my test2 variable that I use in the same .html works, example:
<div class="col mb-4" *ngFor="let t2 of test2">
<h5 class="card-title">{{ t2.nom }}</h5>
What I don't understand is why one displays and the other does not! I however put both in the ngOnInit() so that it is treated in priority!
in my service I made a console.log of what my https requests return to me, and everything is working correctly... This is what the google chrome console shows me :
I hope I have provided you with all the necessary information, sorry if my words are not correct I am not a professional. Thank you in advance for reading!
Assuming that the service method getSiteById was on line 30 when you got the log entries from your message, the http request is returning an array:
Your functions are expecting an object instead. So when you assign your variable test1 here:
this.test1 = site;
it becomes an array with a single element.
There are a few option to resolve this:
this.test1 = site[0];
public getSiteById(id : number): Observable<ISite> {
return this.http.get<ISite[]>(this.HOTEL_API_URL + "test/" + id).pipe(
map(data => data[0]),
catchError(this.handleError)
);
}