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
?
Yes every time when it subscribe or value changes it will unsubscribe automatically this is the magic of async pipe.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With