I
I
Ivan2017-10-21 13:12:44
JavaScript
Ivan, 2017-10-21 13:12:44

How to process an HTTP request in a service, and pass an observable down the chain?

There is the following structure:
59eb1c74ea9ab217020615.png
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);
   }
}

UserService.ts
export class UserService{
      constructor(private http: MyHttpService) {}

      getUsers(){
        return this.http.getData('http://getUsers.com');
      }
 }

I tried to do it through .switchMap but something was unsuccessful, the data does not arrive in the component, or am I doing something wrong?
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 answer(s)
D
Dasha Tsiklauri, 2017-10-21
@dasha_programmist

1) If the version is >=4.3, then you can already use HttpClientfrom @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 question

Ask a Question

731 491 924 answers to any question