自定义 Angular 管道采用字符串和 returns Observable<string>。不知何故缺少变化检测
Custom Angular pipe takes string and returns Observable<string>. Somehow missing change detection
所以,我正在编写自定义管道。它以字符串作为参数,将其与从 ComplexObservablService 获得的 Observable 和 returns Observable 组合。 (是的,我简化了一点。)
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;
}));
}
}
然后,在我的组件中(基本上)有以下代码。
<span>{{ stringFromComponent | customPipe | async }}</span>
<button (click)="pushNewValueToComplexObservableService()">click me</button>
现在,ComplexObservableService 在实例化时会发布一个初始值。因此,当页面最初加载时,会立即返回一个值,并由异步管道正确呈现。
问题是,当按下按钮并且 ComplexObservableService 发布一个 second 值时,HTML 不会重新呈现。因为 stringFromComponent
的值没有更新,只有 ComplexObservableService 发布的值,不知何故 Angular 变得混乱,变化检测的事情不执行;从未达到 console.log
语句。
有什么方法可以做我想做的事吗?
谢谢!
我认为不纯的管道会像这样解决这个问题:
@Pipe({ name: 'customPipe', pure: false})
所以,我正在编写自定义管道。它以字符串作为参数,将其与从 ComplexObservablService 获得的 Observable 和 returns Observable
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;
}));
}
}
然后,在我的组件中(基本上)有以下代码。
<span>{{ stringFromComponent | customPipe | async }}</span>
<button (click)="pushNewValueToComplexObservableService()">click me</button>
现在,ComplexObservableService 在实例化时会发布一个初始值。因此,当页面最初加载时,会立即返回一个值,并由异步管道正确呈现。
问题是,当按下按钮并且 ComplexObservableService 发布一个 second 值时,HTML 不会重新呈现。因为 stringFromComponent
的值没有更新,只有 ComplexObservableService 发布的值,不知何故 Angular 变得混乱,变化检测的事情不执行;从未达到 console.log
语句。
有什么方法可以做我想做的事吗?
谢谢!
我认为不纯的管道会像这样解决这个问题:
@Pipe({ name: 'customPipe', pure: false})