Home > other >  Custom Angular pipe takes string and returns Observable<string>. Somehow missing change detect
Custom Angular pipe takes string and returns Observable<string>. Somehow missing change detect

Time:12-18

So, I'm writing a custom Pipe. It takes a String as an argument, combines it with an Observable obtained from ComplexObservablService, and returns an Observable<String>. (Yes, I'm simplifying a bit.)

import { Pipe, PipeTransform } from '@angular/core';
import { ComplexObservableService } from 'myFiles';

@Pipe({
  name: 'customPipe'
})
export class CustomPipe implements PipeTransform {

  constructor(private $complexObservableService: ComplexObservableService) { }

  transform(input: string): Observable<string> {
    return this.$complexObservableService.getStringObservable().pipe(map(str => {
      console.log('here');
      return str   input;
    }));
  }
}

Then, in my component I have (essentially) the following code.

<span>{{ stringFromComponent | customPipe | async }}</span>
<button (click)="pushNewValueToComplexObservableService()">click me</button>

Now, ComplexObservableService publishes one initial value when it's instantiated. Therefore, when the page initially loads, one value is immediately returned, and rendered correctly by the async pipe.

The problem is, when the button is pushed, and ComplexObservableService publishes a second value, the HTML is not rerendered. Because the value of stringFromComponent has not been updated, but only the value published by ComplexObservableService, somehow Angular gets confused and the change detection things don't execute; the console.log statement is never reached.

Is there any way to do what I'm trying to do?

Thanks!

CodePudding user response:

I think impure pipe will fix this like this:

@Pipe({ name: 'customPipe', pure: false})
  • Related