服务:
import { Injectable } from '@angular/core';
import { BehaviorSubject} from 'rxjs/BehaviorSubject';
import {Subject} from 'rxjs/Subject';
@Injectable()
export class RadioButtonService {
public Status_Subject: Subject<string> = new BehaviorSubject<string>('x;y');
constructor() {
}
public setRadioChecked(instance: string, id: string ) {
const key = instance + ';' + id;
this.Status_Subject.next(key);
}
}
export class RadioButtonComponent implements AfterViewInit, OnDestroy {
@Input() id: string;
@Input() instanceId: string;
@Input() group: string;
isdisabled = false;
ischecked = false;
subj: Subject<string>;
constructor(private radSvc: RadioButtonService) {
this.subj = this.radSvc.Status_Subject;
}
ngAfterViewInit() {
this.subj.subscribe(
(key) => {
const parts = key.split(';');
this.ischecked = (key[0] !== this.instanceId || key[1] !== this.id ? false : true );
}
);
}
ClickEvent($event) {
if (!this.isdisabled) {
this.ischecked = !this.ischecked;
this.radSvc.setRadioChecked(this.instanceId, this.id); // tell the world we got clicked
// send to Store(instanceId, id, value);
}
}
AfterViewInit()初始化组件的主题(我认为),并等待服务调用。
当我点击一个单选按钮时,组件中会调用ClickEvent,我在服务中进入setRadioChecked函数,下一个(键)似乎会执行,但组件的AfterViewInit subscribe永远不会捕捉到它。
感谢您的帮助:-)