Answer the question
In order to leave comments, you need to log in
How to process an HTTP request in a service, and pass an observable down the chain?
There is the following structure:
But I don't understand how to get an error in the UserService, handle it in the ErrorService, and get the result in the component.
And if there is no error, then send an observable to the component in order to subscribe to it there and receive data. Or even send data to the component at once, but how then to do it asynchronously?
MyHttpService.ts
export class MyHttpService {
constructor(private http: Http) {}
getData(url: string): Observable<any> {
return this.http.get(url);
}
}
export class UserService{
constructor(private http: MyHttpService) {}
getUsers(){
return this.http.getData('http://getUsers.com');
}
}
getUsers(){
return this.http.getData('http://getUsers.com')..switchMap(
(response): any => {
200 === response.status ? Observable.of(this.sta) : console.log('222');
};
}
Answer the question
In order to leave comments, you need to log in
1) If the version is >=4.3, then you can already use HttpClient
from @angular/common/http
2) It is not clear why the data should arrive in the component, because for some reason you hid the component code
3)
// service
getUsers(){
return this.http.get('url').map(resp=>resp.json()||[]);
}
// component
// 1 вариант
users: [];
// 2 вариант
users: Observable<[]>;
ctor(uSvc:UserService){
// 1 вариант
uSvc.getUsers().subscribe(users=>this.users=users);
// 2 вариант
this.users = uSvc.getUsers();
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question