angular2 –通过自定义管道使用全局服务 [英] angular2 – use global service through a custom pipe

查看:204
本文介绍了angular2 –通过自定义管道使用全局服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用角度2玩一些游戏.到目前为止,我建立了一个拥有接口的全局服务.其他组件正在使用此全局服务的接口.如果通过组件更改了接口,则子组件也将更改接口.

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

这里也是柱塞

推荐答案

仅当值或参数更改时才执行纯管道.

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

这篇关于angular2 –通过自定义管道使用全局服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆