问题
I am playing around a little bit with angular 2. So far I built a global service that holds an interface. Other components are using the interface of this global service. If the interface is changed through a component the interface will also change for the child components.
Now I am trying to handle this through a pipe. But when I am changing the interface value through a child component the interface values within the other components won't change.
This is what I got so far:
import { Pipe, PipeTransform, EventEmitter } from '@angular/core';
import { GlobalService } from './global-service'
import { MyInterface } from './my-interface'
@Pipe({name: 'myPipe'})
export class MyPipe implements PipeTransform {
private value: string;
private _interface: MyInterface;
private interfaceChanged: EventEmitter<MyInterface>;
constructor(private globalService: GlobalService) {
this._interface = globalService._interface;
this.interfaceChanged = this.globalService
.interfaceChanged
.subscribe((newInterface: MyInterface) => {
this._interface = newInterface;
});
}
transform(value: string, args: any[]): string {
for (var key in this.language) {
if (key == value) {
this.value = this._interface[key];
break;
}
}
return this.value;
}
}
Here also is a Plunker
回答1:
Pure pipes are only executed when the value or a parameter changed.
You can configure the pipe to become an impure pipe, then the pipe will be executed every time change detection runs. This can have serious performance impact though
@Pipe({name: 'myPipe', pure: false})
来源:https://stackoverflow.com/questions/38692577/angular2-use-global-service-through-a-custom-pipe