如何在component.ts代码而不是html中编写ngxs异步可观察插值?

时间:2018-06-02 05:40:52

标签: javascript angular

在我的Angular应用程序的html中,我可以写这个,它确实会从变量中提取“标题”并在屏幕上显示:

我的component.html

以下工作正常
<input matInput value="{{ (app$ | async).myTitle.match('title: &quot;(.*)&quot;')[1] }}" placeholder="My Title" #title>

我想做一些代码重用并将其插入我的component.ts

我尝试重构将代码移到component.ts但得到错误

所以我尝试了我的component.ts

  getTitle(): Observable<string> {
    return this.app$.map(state => {
        return state.myTitle.match('title: &quot;(.*)&quot;')[1];
      }
    );
  }

然后尝试将html简化为:

value="{{ getTitle | async }}

然后我收到错误:

  

InputformComponent.html:7错误错误:InvalidPipeArgument:'function   (){           return this.app $ .map(function(state){               return state.everyBootstrapThemeConfig.match('title:“(。*)”')[1];           });       }'for pipe'AsyncPipe'       在invalidPipeArgumentError(common.js:4232)       at AsyncPipe.push ../ node_modules/@angular/common/fesm5/common.js.AsyncPipe._selectStrategy   (common.js:4839)       at AsyncPipe.push ../ node_modules/@angular/common/fesm5/common.js.AsyncPipe._subscribe   (common.js:4829)       at AsyncPipe.push ../ node_modules/@angular/common/fesm5/common.js.AsyncPipe.transform   (common.js:4811)       在Object.eval [as updateDirectives](InputformComponent.html:7)       at Object.debugUpdateDirectives [as updateDirectives](core.js:11914)       在checkAndUpdateView(core.js:11307)       在callViewAction(core.js:11548)       在execComponentViewsAction(core.js:11490)       在checkAndUpdateView(core.js:11313)

我可能错过了如何访问observable并返回getTitle()

中字段的可观察对象

1 个答案:

答案 0 :(得分:1)

您将函数对象getTitle传递给异步管道而不是其调用getTitle()

value="{{ getTitle | async }}

而不是

value="{{ getTitle() | async }}

这就是为什么错误消息显示InvalidPipeArgument: function,因为“给定的函数是此管道的无效参数。”