我知道有异步管道,使用observables你可以订阅并在更新时获取值。
我正在尝试创建一个简单的管道,它将使用其代码获得分类器的转换,但它使用observable来实现,因此它是异步的。我能以某种方式等待异步操作完成然后返回结果吗?什么是最佳方式? 我不认为async Pipe是我正在寻找的,因为它基本上是一个带有它自己的HTML的组件。
代码
@Pipe({
name: 'translate'
})
export class Translate implements PipeTransform {
constructor(public translateContext: TranslateContext) {
}
transform(value: any, classification: string): any {
this.translateContext.getTranslation(classification).subscribe(res => {
return res.get(value.toString());
});
}
}
我想在HTML中使用以下管道,如下所示
{{code | translate: classificator }}
我怎么能解决这个问题,从管道中得到这个值。
return res.get(value.toString());
答案 0 :(得分:2)
更改为:
transform(value: any, classification: string): any {
return this.translateContext.getTranslation(classification).map(res => {
return res.get(value.toString());
});
}
并使用它:
{{code | translate:classificator | async }}
这里的想法是返回一个包含你的值的observable,然后使用async
订阅observable。这将在模板中显示映射值。