Joh*_*ing 6 observable rxjs typescript angular
我打电话给MS Graph获取用户的照片:
// 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();
Run Code Online (Sandbox Code Playgroud)
然而,许多用户没有照片.在我想做到这一点的情况是创建一些默认照片对象URL(之一这些也许),并发出从观测.或者甚至只是undefined
从Observable 发出一个,我可以通过显示一些默认图像在前端处理.
我知道我的捕获正在解雇,因为我在浏览器控制台中看到了这个:
没有该用户的照片xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx!返回默认值...(输出编辑)
我实际上为每个用户提供了许多不同的数据位,每个用户都在自己的Observable中.然后我将每个Observable转换为Promises,然后Promise.all()
对所有这些进行转换.
// let's pull all of this together to form a ConcreteUser
return Promise.all([photo$, ...])
.then(values => {
const photo = values[0];
...
Run Code Online (Sandbox Code Playgroud)
问题是用户的照片为404,整个Promise.all
中止,我无法检索用户.
我已经尝试在photo$
observable中捕获错误并发出一个undefined
(我打算稍后处理),但它似乎没有做我想要的.
我如何处理我的Observable中的404s,并发出其他东西(也许undefined
)而不是杀死observable?
我想我可能已经弄明白了.一个提示潜伏在浏览器控制台中......
TypeError:您提供了"undefined",其中包含了一个流.您可以提供Observable,Promise,Array或Iterable.
阅读关于错误处理的RxJs 文档显示他们正在做我正在尝试做的事情,所以我对此感到有些困惑.但后来我注意到在文档中他们称之为神秘函数getCachedVersion()
,我假设它返回了一个真正的缓存函数.但是,如果他们返回了Observable.of()
一些实际缓存的东西,那么这可能会解释它.
当我将我的catch代码更改为:
.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);
}
})
Run Code Online (Sandbox Code Playgroud)
......一切都开始奏效了.
归档时间: |
|
查看次数: |
2297 次 |
最近记录: |