'Why is Observable Subscribe Making My Class Empty
I have created a service, when the service is called and do a console log of the parameter in the subscriber it shows my class empty. I have used Observable's in the past and I have never ran into this issue. If it serves me right the parameter can be any name. Code snippet below.
My service
export interface Products{
_id: string,
name: string
}
@Injectable({
providedIn: 'root'
})
export class SearchService {
constructor(private http:HttpClient) { }
rootUrl = '/api'
searchProducts(query:string) {
console.log("Does it get my searchProducts");
return this.http.post<{payload: Array<Products>}>(this.rootUrl + '/getProducts', {payload: query}, {
headers: new HttpHeaders({'Content-Type': 'application.json'})
}).pipe(
map(data => data.payload)
);
}
}
My Component.ts
sendData(event:any){
let query:string = event.target.value;
this.searchService.searchProducts(query.trim()).subscribe(results =>{
console.log(results); //results is a empty array
});
}
Can anyone tell me?
Solution 1:[1]
Does your API response contain a field called payload? If so, does it have a value?
I recommend moving your console log up a level so that you can see what the API response is and what fields it has. Something like this,
searchProducts(query:string) {
console.log("Does it get my searchProducts");
return this.http.post<{payload: Array<Products>}>(this.rootUrl + '/getProducts', {payload: query}, {
headers: new HttpHeaders({'Content-Type': 'application.json'})
}).pipe(
map(data => {
console.log('API Response => ', data);
return data.payload
})
);
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | David Kidwell |
