来自服务的Angular2多播

时间:2016-12-19 06:49:56

标签: angular angular2-observables

我有一个更新我的数据库的服务我希望它更新我的祖父母和父组件。

我得到的行为是祖父母组件从服务获得响应。如果我在祖父母中注释掉订阅代码,那么我会看到父行为。我想要的是每次更改progressBar $

的值时都要响应的组件

服务代码

export class CompetitionService {
  progressBarSubject = new Subject<boolean>();
  progressBar$ = this.progressBarSubject.asObservable();
  private subscription: Subscription=new Subscription();

  constructor(
    private loginService: LoginService,
    private http: Http
  ) { }

  initializeCompetition(compDate: string) {
    this.progressBarSubject.next(true);


    const login = this.loginService.getLogin();
    const url = AppSettings.API_ENDPOINT + "competition/addCompetition";

    let headers = new Headers();
    headers.append('C247Token', login.getToken())

    let body = { 'C247Token': login.getToken(), 'compDate': compDate };

    //execute http (must have a corisponding subscribe)
    this.subscription = this.http.post(url, body, { headers: headers })
      .subscribe(res => {

        this.progressBarSubject.next(false);
      },
      err => {
        this.handleError(err);
      });


  }

祖父母组件

 private isProgressBarOn: boolean = false;
  private subscription: Subscription = new Subscription();

  constructor(private loginService: LoginService,
    private competitionService: CompetitionService,
    private cd: ChangeDetectorRef,
    private router:Router
  ) { }

  ngOnInit() {    
    this.subscription = this.competitionService.progressBar$
      .subscribe(
      response => {
        this.isProgressBarOn = response;
        this.cd.detectChanges();
        //alert("Stop "+'"'+this.isProgressBarOn+'"');

      }
      );//*/
  }

父组件:

  ngOnInit() {
    this.initForm();
    this.subscription = this.competitionService.progressBar$
    .subscribe(response=>{
      console.log('hit '+response);
    }

1 个答案:

答案 0 :(得分:0)

谢谢大家。事实证明问题出在router-outlet标签上。

当你将ngIf与路由器标签结合使用时,似乎Angular2中存在一个错误。一旦我将祖父母ngIf更改为[隐藏],两个订阅都按预期启动。

新的祖父母代码模板代码是

<!-- old code <div *ngIf-"isProgressBarOn"> -->
<div [hidden]="isProgressBarOn">
    <router-outlet></router-outlet>
</div>

之前服务会更改isProgressBar的值,并通知父级。

感谢您的所有帮助