Angular的共享服务。我如何实现观察者?

时间:2018-06-11 22:38:12

标签: angular

我有一个组件子组件,它是一个带有按钮的表,用于添加新的注册表。在这个例子中,我想用这个共享服务发出一个事件,而Component Parent是这个共享服务的观察者。 因此,通过此示例,我无法捕获事件并将其分配给Component Parent中的变量。 任何人都可以解释我如何使用Angular来做到这一点?

组件子项:

export class ComponentChild implements OnInit {


    constructor(
        private ss: SharedService,
    ) {
        this.ss = ss;
    }

    ngOnInit() {
        this.getData();
    }

    add() {
        this.ss.show();
    }
}

SharedService

@Injectable()
export class SharedService {
    @Output() fire: EventEmitter<any>;

    show() {
        this.fire.emit(true);
    }
}

组件父

export class ComponentParent implements OnInit {

    add: Boolean;
    subscription: any;

    constructor(
        private ss: SharedService,
    ) {
        this.ss = ss;
        this.ss.fire.subscribe(item => {
            this.add = item;
        });
    }

    ngOnInit() {
    }

}

1 个答案:

答案 0 :(得分:1)

而不是EventEmitter(通常用于允许您将函数应用于组件可以侦听的组件模板中的事件),而是使用可观察的为Subject

您的共享服务没有父级,它是单身,因此EventEmitter不适合此要求。

所以你的服务将是

fire: Subject<any> = new Subject<any>();

然后,您想要成为观察者的任何组件都可以订阅对它的更改。

this.ss.fire.subscribe((item: any) => {
    this.add = item;
}

现在,只要SharedService中的主题更新了其值,您的观察者就可以更新其局部变量。