Angular2 multicast from service

278 views Asked by At

I have a service that updates my database I want it to update both my Grandparent and parent components.

The behavior I am getting is that the Grandparent component is getting the response from the service. If I comment out the subscribe code in the Grandparent, then I see the parent behavior. What I want is both components to respond every time I change the value of the progressBar$

Service code

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);
      });


  }

Grandparent Component

 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+'"');

      }
      );//*/
  }

Parent Component:

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

There are 1 answers

0
Ken On

Thank you to all. It turns out that problem was with the router-outlet tag.

It seems there is a bug in Angular2 when you use ngIf in conjunction with the router tag. Once I changed the Grandparent ngIf to [hidden], both subscriptions fired as expected.

The new Grandparent Code template code is

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

as before the service changes the value of isProgressBar and also notifies the parent.

Thank you for all of your help