[英]Send data to all subscribers elements with observable - angular2
我想將數據發送到稱為“模式”的所有元素,但是只有其中一個接收消息。
我有服務:
@Injectable()
export class ModalService {
private _isOpen = new Subject();
isOpen$ = this._isOpen.asObservable();
open(id: string) {
this._isOpen.next({isOpen: true, id: id});
}
close(id: string) {
this._isOpen.next({isOpen: false, id: id});
}
和組件:
import {Component, Input} from 'angular2/core';
import {Observable} from 'rxjs/Observable';
import {Subject} from 'rxjs/Subject';
import {ModalService} from './modal.service';
@Component({
selector: 'modal',
template: `
<ng-content></ng-content>`,
styleUrls: ['app/workshop/modal.component.css'],
providers: [ModalService],
})
export class ModalComponent {
@Input() ID;
private show = false;
constructor(private _modal: ModalService) {
this._modal.isOpen$.subscribe(
(value) => {
console.log(value)
if(this.ID === value.id) {
this.show = value.isOpen;
}
}
);
}
open() {
this._modal.open(this.ID);
}
close() {
this._modal.close(this.ID);
}
}
一切正常,但當我想在其他任何組件中注入服務並向其余訂閱者發送消息時,問題就會出現。 我不知道如何為“模式”的所有元素類型共享消息。 我可以鈎住DOM元素,但是組件有問題。 我怎樣才能將所有“模態”元素掛鈎到可觀察的位置?
感謝幫助
實際上,您需要為所有這些組件共享同一實例。 為此,請在主要組件的providers
屬性中設置服務:
@Component({
(...)
providers: [ ModalService ]
})
export class AppComponent {
(...)
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.