Angular 2在自定义单选按钮中使用BehaviorSubject

Angular 2在自定义单选按钮中使用BehaviorSubject,angular,behaviorsubject,Angular,Behaviorsubject,我需要建立自定义单选按钮。当选择一个时,它调用一个服务,该服务将向所有已订阅的单选按钮(包括调用者)发送其标识符。如果subscribe发现key instance+id与自身不相同,它将取消选中自身,否则匹配的instance+id(实际上是调用者)将保持选中状态。 服务: import { Injectable } from '@angular/core'; import { BehaviorSubject} from 'rxjs/BehaviorSubject'; import {Subj

我需要建立自定义单选按钮。当选择一个时,它调用一个服务,该服务将向所有已订阅的单选按钮(包括调用者)发送其标识符。如果subscribe发现key instance+id与自身不相同,它将取消选中自身,否则匹配的instance+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初始化组件的主题,我认为它应该等待服务调用。 当我单击radiobutton时,组件中会调用ClickEvent,我在服务中进入setRadioChecked函数,nextkey似乎会执行,但组件的AfterViewInit subscribe永远不会捕捉到它

我错过了什么


感谢您的帮助:-

我用您的代码创建了一个plunkr,我可以让一切正常工作:plnkr.co/edit/WzZvZNU6S8uPOb85gqZO

我用您的代码创建了一个plunkr,我可以让一切正常工作:啊!!!是的,它是。。。将plunker的详细信息与我自己的代码进行比较,我发现我弄乱了id中的一行代码。非常感谢您的帮助。我希望我能把这个作为答案!瑜伽士,没问题。很高兴知道这有帮助。作为答复张贴。