2016-12-21 12 views
1

私はルートのparamsを取得し、これが最初のエラーまで、正常に動作サービスから角度2つのチェーンのルートのparamsおよびHTTPサブスクリプション

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

データを取得しようとしています。エラーが発生した後、この行はもうparams => this.noteService.GetParams(params['id'])を呼び出しません。

更新私はこのような何かを書くことができますが、私は

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

マイサービス

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

良い方法があると思います。このanswerは私に何が起こっているかを理解するためのたくさん助けに。 Observable.throw(error)を呼び出すと、paramsをルーティングするサブスクリプションがエラーで停止します。だから、エラーを投げるのではなく、ただ空の観測可能なものを返す必要があります。

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)); 
} 
+0

どのようなエラーが表示されていますか? –

+0

504(ゲートウェイタイムアウト) – user2156149

答えて

1

私は今、githubのユーザーアプリケーションを構築し、同じ問題を抱えていたんです。ここ は私のために機能するソリューションです:

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); 
    } 

、基本的にflatMap operatorは、トリックを行います。 link他の質問へ RxJSオブザーバブルを連鎖させる方法がわかりました

関連する問題