我正在尝试实现异步管道 在内部,管道使用返回承诺的第三方组件 基本上,它查找字典,如果找到键,则返回相应的字符串值。如果找不到,则会引发错误。我想处理未找到的部分,并在这种情况下返回默认值。我的问题是这部分-不管我尝试什么,订阅的结果都是第三方组件返回的错误,没有返回的值。代码如下:
@Pipe({ name: 'Lookup' })
export class LookupPipe implements PipeTransform
{
transform(value: number, dataSource: BaseDataSourceAbstract, propName: string = "Text", sDefault: string = undefined, sNullValue: string = undefined): Observable<string>
{
//If default value was not set, set it to the original value
if (sDefault == undefined && value != undefined) sDefault = `${value}`;
//Get value
var promise = dataSource.Store.byKey(value)
.then(result =>
{
//If not found
if (result == undefined) return sDefault;
//Get result from the selected property
var sReturn: string = result[propName];
//Handle null
if (sReturn == "" || sReturn == undefined) sReturn = sNullValue;
//Finish
console.log("Found: " + sReturn)
return sReturn;
})
.catch(reject =>
{
console.log("Not found")
return sDefault;
});
return from(promise);
}
}
//use it:
var x = new LookupPipe;
x.transform(null, MyDataSource, 'Name').subscribe(s =>
{
console.log(s)
});
}
我希望s是我的默认值。我确实在控制台中看到“未找到” 但是由于某种原因,s是从byKey调用
返回的异常消息。答案 0 :(得分:0)
我认为您应该向then添加第二个回调函数:
p.then(function(value) {
// fulfillment
}, function(reason) {
// rejection
// return your default value here.
});
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then
答案 1 :(得分:0)
看起来与第三方组件相关。与他们解决了