user2156149
user2156149

Reputation: 53

Angular 2 chain route params and http subscriptions

I am trying to get route params and then get data from the service

 this.route.params
   .switchMap(params => this.service.getData(params['id']))
   .subscribe(value => this.value = value,
     error => console.log(error));

This works fine, until first error. After the error this line doesn't calls no more params => this.noteService.GetParams(params['id']).

I can write something like this, but i think there is a better way

  this.route.params.subscribe(
    params => {
      this.service.getData(params['id']).subscribe(
        result => console.log(result),
        error => console.log(error))
  });

My service

public getData(id): Observable<any> {
  return this.http.get('api/data/' + id)
    .map(data => data.json())
    .catch(error => Observable.throw(error));
 }

Update This answer helped me a lot to understand what is going on. When I call Observable.throw(error) subscription to route params stops with an error. So instead of throwing error I just need to return empty observable.

my.component.ts

this.route.params
  .switchMap(params => this.service.GetData(params['id']))
  .subscribe(result => {
    if (result) this.data = result; 
    else console.log('error');
  });

my.service.ts

public GetData(id): Observable<any> {
   let url = 'api/data' + id;
   return this.http.get(url)
    .map(data => data.json())
    .catch(error => Observable.of(null));
}

Upvotes: 1

Views: 1544

Answers (1)

Nikolay Nikolaev
Nikolay Nikolaev

Reputation: 11

I'm building a github users application right now and had the same problem. Here is a solution that works for me:

users.service.ts

public getByUsername(username: string): Observable<any[]> {
        return this.http
            .get(`${this.url}/${username}`)
            .map((res: Response) => res.json());
    }

user.component.ts

ngOnInit() {
        this.sub = this.route.params
            .flatMap((v: any, index: number) => {
                return this.usersService.getByUsername(v.name);
            })
            .subscribe(data => this.user = data);
    }

So, basically the flatMap operator does the trick. Here is link to another question, helping me to figure out how things work with chaining RxJS Observables

Upvotes: 1

Related Questions