Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inject AsyncPipe in another pipe

Tags:

angular

Use case : I defined a CustomError like this :

interface {
  message?: string;
  i18nMessage?: string;
}

And I define a DisplayErrorPipe to display the error. If message is defined, the pipe returns it. Else, if i18nMessage is defined, the pipe returns a Observable<string> (which will emit the translated error).

So the pipe should be used like this :

{{ customError | displayError }}

DisplayErrorPipe might return an Observable but I would like to avoid having to pipe async every time

{{ customError | displayError | async }}

Hence, I need to inject AsyncPipe in DisplayErrorPipe so that I can automatically pipe async when the pipe returns an Observable<string>.

So I tried :

constructor(private asyncPipe: AsyncPipe) {}

but I get an error :

NullInjectorError: No provider for AsyncPipe!

I can't find which module I should import in order to be able to inject AsyncPipe.

Until now, the only solution I have is :

constructor(private _ref: ChangeDetectorRef) {
  const asyncPipe = new AsyncPipe(_ref);
}

This works but is likely to break if the constructor of AsyncPipe changes.

Question : How to properly inject AsyncPipe ?

like image 686
Arnaud Denoyelle Avatar asked Feb 28 '19 15:02

Arnaud Denoyelle


People also ask

Does pipe automatically subscribe?

Yes every time when it subscribe or value changes it will unsubscribe automatically this is the magic of async pipe.

How does async pipe work?

The async pipe subscribes to an Observable or Promise and returns the latest value it has emitted. When a new value is emitted, the async pipe marks the component to be checked for changes. When the component gets destroyed, the async pipe unsubscribes automatically to avoid potential memory leaks.

Does async pipe triggering change detection?

It means that the component with the async pipe will be marked for check every time a new value is emitted. And Angular will check the component next time it runs change detection even if the value hasn't changed.

Does async pipe automatically unsubscribe?

AsyncPipes for Observables automatically subscribes to the observable, renders the output, and then also unsubscribes when the component is destroyed. So, we don't need to handle the cleanup logic ourselves. There is no need to unsubscribe manually in the component.


1 Answers

You just need to register the AsyncPipe as a provider in the module that component is declared in. I think Angular doesn't register them as services by default in the DI system.

like image 149
bgraham Avatar answered Nov 01 '22 02:11

bgraham