First, if you want to map the data return from an Observable to something else, pass the map()
operator to the Observable's pipeline. Like this:
getSamples(): Observable<Cat[]>{
return this.http.get(this.url).pipe(map(response => { .... });
}
But if the get request is simply going to return the Cat[]
data, then you dont have to map it:
getSamples(): Observable<Cat[]>{
return this.http.get(this.url);
}
Secondly, if you want to active the Observable returned from getSamples()
, subscribe()
to it not subscriber()
to it.
And it really important to know that the subscribe()
function is going to return a subscription of the Observable you subsrcibed to, not the data it contain
Returning an data from a observable inside a function is not a good approach because get()
is a asynchronous function, it need to wait for your http request to complete first in order to return the right data/error. So the better approach is to active the observable somewhere outside and pass the logic that need the cat[]
data into it:
ngOnInit() {
this.service.getsamples().subscribe(response => {
console.log(response)
// Do stuffs with respone data
},err =>{
console.log(err)
// Do things with error
});
}