Arnaud Denoyelle
Arnaud Denoyelle

Reputation: 31273

Inject AsyncPipe in another pipe

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 ?

Upvotes: 9

Views: 1987

Answers (1)

bgraham
bgraham

Reputation: 2027

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.

Upvotes: 7

Related Questions