find方法不适用于RxJs Observable

时间:2017-01-09 15:18:49

标签: angular typescript rxjs

我在angular2应用程序中使用NgRx。但是,我在Observable上使用find方法时遇到了一些困难。

我的应用程序的翻译来自外部应用程序,通过休息,并作为键值对象存储在NGRX存储中。该对象具有带代码的关键变量和转换变量。

当我尝试实现find方法以找到正确的翻译对象时,它不起作用。

@Pipe({


name: 'translate',
})
export class TranslatePipe implements PipeTransform, OnInit {

  uiMessages$ = this.sb.uiMessages$;

  constructor (private sb: AppSandbox) {}

  transform(value: string, args: any[]): any {
    return this.uiMessages$.find((uiMessage: UiMessage) => (uiMessage.key === value)).translation;
  }

有谁知道我做错了什么?

由于

2 个答案:

答案 0 :(得分:0)

假设uiMessages$是一个Observable,你不能只使用.find并期望一个对象,因为find是一个rxjs-operator而rxjs-operators将始终返回一个Observable。 / p>

你能做的是:

transform(value: string, args: any[]): any {
    return this.uiMessages$
        .switchMap((uiMessages: UiMessage[]) => Observable.from(uiMessages))
        .find((uiMessage: UiMessage) => (uiMessage.key === value))
        .map((uiMessage: UiMessage) => uiMessage.translation);
}

然后另外使用async - 管道:

<div>{{'foo' | translate | async}}</div>

答案 1 :(得分:0)

尝试在找到之后添加类型。它应该看起来像这样

transform(value: string, args: any[]): any {
    return this.uiMessages$.find<UiMessage>(uiMessage => (uiMessage.key === value)).translation;
}