【问题标题】:angular2 – use global service through a custom pipeangular2 - 通过自定义管道使用全局服务
【发布时间】:2016-08-01 06:49:44
【问题描述】:

我正在玩 angular 2。到目前为止,我构建了一个包含接口的全局服务。其他组件正在使用这个全局服务的接口。如果通过组件更改界面,则子组件的界面也会发生变化。

现在我正在尝试通过管道处理这个问题。但是当我通过子组件更改接口值时,其他组件中的接口值不会改变。

这是我目前得到的:

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;
    }
}

这里也是Plunker

【问题讨论】:

    标签: typescript angular pipe


    【解决方案1】:

    纯管道仅在值或参数更改时执行。

    您可以将管道配置为不纯管道,然后每次更改检测运行时都会执行该管道。不过,这可能会对性能产生严重影响

    @Pipe({name: 'myPipe', pure: false})
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-07-03
      • 2016-06-18
      • 2016-09-08
      • 2016-12-24
      • 2017-03-20
      • 1970-01-01
      • 2017-05-13
      • 2017-05-15
      相关资源
      最近更新 更多