'How to get return value from subscriber function in angular?
I am calling a function which has a subscriber function in it. This function must return an array, but it's giving an error:
subscription is missing.
get():obeservable<cat[]>{
return this.service.getsamples().subscriber(response=>{
return <cat[]>(response);
});
}
getSamples(){
return this.http.get(this.url)
.map(response=>{
return <cat[]>response
});
}
How to achieve this?
Solution 1:[1]
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
});
}
Solution 2:[2]
Simple observable setup would be something like:
@Injectable()
export class SomeService {
constructor(private readonly httpClient: HttpClient) {}
public getData(): Observable<Cat[]> {
return this.httpClient.get<Cat[]>('http://something.com')
.pipe(catchError(err) => this.handleError(err));
}
private handleError(err: HttpErrorResponse): Observable<Cat[]> {
// do something
const result: Cat[] = [];
return of(result);
}
}
And hook up to it:
@Component({...})
export class SomeComponent implements OnDestroy {
constructor(private readonly service: SomeService) {}
public doSomething(): void {
this.service.getData()
.subscribe((x: Cat[]) => {
alert(`Received ${x.length} cats`);
});
}
}
At some point, the Angular HttpClient got somewhat smarter and will handle mapping the return types, so you can make your own generic HttpService of some description and make use of this.httpClient.get<T>(...), or just on a per-usage basis do as the above and ensure you provide your type to the method this.httpClient.get<Cat[]>(...).
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 | |
| Solution 2 |
