Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write ngxs async observable interpolation in component.ts code instead of html?

In my Angular app's html, I could write this and it would indeed extract from the variable the "title" and show it on screen:

Below works fine from my component.html:

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

I want to do some code reuse and insert that to my component.ts

I tried to refactor move the code to component.ts but get error:

So I tried in my component.ts

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

And then tried to simplify the html to be:

value="{{ getTitle | async }}

but then I get error:

InputformComponent.html:7 ERROR Error: InvalidPipeArgument: 'function () { return this.app$.map(function (state) { return state.everyBootstrapThemeConfig.match('title: "(.*)"')[1]; }); }' for pipe 'AsyncPipe' at 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) at Object.eval [as updateDirectives] (InputformComponent.html:7) at Object.debugUpdateDirectives [as updateDirectives] (core.js:11914) at checkAndUpdateView (core.js:11307) at callViewAction (core.js:11548) at execComponentViewsAction (core.js:11490) at checkAndUpdateView (core.js:11313)

I'm probably missing how to access the observable and return an observable of the field in getTitle()

like image 266
Jas Avatar asked Nov 08 '22 06:11

Jas


1 Answers

You're passing the function object getTitle to the async pipe instead of its invocation getTitle().

value="{{ getTitle | async }}

instead of

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

That's why the error message says InvalidPipeArgument: function as in "given function is an invalid argument for this pipe."

like image 193
Kim Kern Avatar answered Nov 14 '22 21:11

Kim Kern