Angular 2 在自定义 RadioButton 中使用 BehaviorSubject

Angular 2 using BehaviorSubject in custom RadioButton

我需要构建自定义 RadioButton。选择一个后,它会调用一个服务,该服务会将其标识符发送给所有订阅的 RadioButton,包括调用者。如果订阅者发现键(实例 + id)与自己不同,它将取消选中自己,否则匹配的实例 + id(实际上是调用者)将保持选中状态。 服务:

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 函数,next(key) 似乎执行了,但它从未被组件的 AfterViewInit 订阅捕获。

我错过了什么?

感谢您的帮助:-)

我用你的代码创建了一个 plunkr,我能够让一切正常工作:plnkr。co/edit/WzZvZNU6S8uPOb85gqZO