Reputation: 20688
Angular version 8.0.4
How to get data from a generic method which returns an array of Observable type T in angular? This is the function I have written
Generic method to get data
public getData<T> (path: string): Observable<T[]> {
return this.http.get(this.baseUrl + path).subscribe();
// return this.data;
// var ddd: T[];
// return this.http.get<Observable<T[]>>(this.baseUrl + path);
// var data: any = this.http.get(this.baseUrl + path).toPromise();
// console.log(data)
// return of(data);
}
This is the calling function
getRecords(): Observable<Trailers[]> {
var k: any = this.httpService.getData<Trailers>("get_trailers");
console.log(of(k));
return of()
}
Angular 2 older version had something like this
public getObjects<T> (path: string): Observable<T[]> {
return this.http.get(this.baseUrl+path)
.map((response: Response) => <T[]> response.json())
.do(data => console.log('Retrieved data from: ' + this.baseUrl+path))
.catch(error => this.handleError(error, this.router));
}
What is equivalent in angular 0.8 to this ?
Upvotes: 1
Views: 5564
Reputation: 1654
Angular Version: 8.0.2
Function can be like,
get<T>(id: string): Observable<T> {
return this.httpclient.get<T>(this.baseUrl+ '/' + id);
}
Caller can be,
this.service.get<MyModel>(id).subscribe((val:MyModel) => { ... // your business logic });
Upvotes: 2
Reputation: 103
Http Get method returns Observables. To read data from Observables, it needs to subscribe. That is why subscribe() method is used here.
Upvotes: 0
Reputation: 120
In my case I use Observable and Subscribe like this.
Function
getTestStatus() :Observable<any[]> {
return this.httpClient.get(`${this.api}/demo/state`) as Observable<any[]>;
}
Calling
let result;
this.getTestStatus().subscribe((res) => {
result = res
console.log(result);
});
Subscribe work like async / await, if u try to print some data from it, you should do in in subscribe
hope this help, if not u should wait another guys.
Upvotes: 0