2017-03-12 1 views
5

を放出することにより、404ハンドル: RxJs観測可能 - 私はMSグラフは、ユーザーの写真を取得するために呼び出していますデフォルト値

// lets get the photo itself 
    let photo$ = this.graph.get$(`users/${id}/photo/$value`, ResponseContentType.Blob) 
     .map(resp => { 
      return new Blob([resp.blob()], { type: resp.headers.get['Content-Type']}); }) 
     .map(photo => { 
      let urlCreator = window.URL; 
      return this.sanitizer 
       .bypassSecurityTrustUrl(urlCreator.createObjectURL(photo)); 
     }) 
     .catch(function (e) { 
      if(e.status === 404) { 
       // no photo for this user! 
       console.log(`No photo for user ${id}! Returning default...`); 
       return undefined; 
      } 
     }) 
     .toPromise(); 

は、しかし、多くのユーザーが写真を持っていません。その場合、私がしたいのは、デフォルトの写真(おそらく theseの1つ)のオブジェクトURLを作成し、ObservableからそのURLを放出することです。あるいはObservableから undefinedを出しても、私はフロントエンドでいくつかのデフォルトイメージを表示することで処理できます。私は実際にユーザごとにデータの多くの異なるビットで引っ張ってる

No photo for user xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx! Returning default... (output redacted)

、それぞれが独自の観察可能に:私は、ブラウザのコンソールでこれを見るため

私は、私のキャッチが発射されていることを知っています。私はそれからObservableのそれぞれを約束に変換してから、Promise.all()をすべて行います。

// let's pull all of this together to form a ConcreteUser 
    return Promise.all([photo$, ...]) 
     .then(values => { 
      const photo = values[0]; 
      ... 

問題は、ユーザーの写真のための404の場合であり、全体Promise.allが中止され、私は、ユーザーを取得することはできません。

私はの観測可能なエラーをキャッチして、undefined(後で処理する予定です)を送信しようとしましたが、私が望んでいるとは思われません。

Observableで404sを処理するにはどうすればよいですか?observableを強制終了する代わりに何か(おそらくundefined)を放出しますか?

答えて

4

私はこれを理解したかもしれないと思います。ヒントはRxJs documentation on error handlingを読む

TypeError: You provided 'undefined' where a stream was expected. You can provide an Observable, Promise, Array, or Iterable.

...ブラウザのコンソールに潜むた彼らは、私が何をしようとしていることが示されたので、私はこれで混乱ビットでした。しかし、ドキュメントでは、私が実際にキャッシュされたものを返すと仮定した謎関数getCachedVersion()を呼び出したことに気付きました。しかし、代わりにObservable.of()実際のキャッシュされたものが返された場合、それはそれを説明するかもしれません。私は私のキャッチコードを変更した場合

は:

 .catch(function (e) { 
      if(e.status === 404) { 
       // no photo for this user! 
       console.log(`No photo for user ${id}! Returning default...`); 
       return Observable.of(undefined); 
      } 
     }) 

...それはすべての仕事を始めました。

関連する問題