0

I am trying to communicate between two components by service but it's not working for me, and I don't understand why. Please guide me through this. I want to change Page title bar when I change a page.

service

import {Injectable} from '@angular/core';
import {Subject} from 'rxjs/Subject';
@Injectable()
export class UpdatePageTitleService {
  // Observable string sources
  private newTitleSource = new Subject<any>();
  // Observable string streams
  newTitle$ = this.newTitleSource.asObservable();

  changeTitle(title: any) {
    this.newTitleSource.next(title);
    console.log(this.newTitleSource);
  }


}

page component

import {Component, OnInit} from '@angular/core';

import {UpdatePageTitleService} from '../../../../share/updatePageTitle.service';

@Component({
  selector: 'customer-details',
  template: require('./customerDetails.html'),
  styleUrls: ['./customerDetails.scss'],
  providers: [UpdatePageTitleService]
})


export class CustomerDetails implements OnInit {

  constructor(private _updatePageTitleService: UpdatePageTitleService) {

  }

  ngOnInit() {
    this._updatePageTitleService.changeTitle('Details');
  }

}

Title page component

import {Component} from '@angular/core';

import {UpdatePageTitleService} from '../../../share/updatePageTitle.service';

@Component({
  selector: 'ba-content-top',
  styles: [require('./titlePage.scss')],
  template: require('./titlePage.html'),
  providers: [UpdatePageTitleService]
})
export class TitlePage {

  public activePageTitle: string = '';

  constructor(private _updatePageTitleService: UpdatePageTitleService) {

    console.log("sankl");
    this.subscription = this._updatePageTitleService.newTitle$.subscribe(
      title => {
        console.log("title 1 " + title);
        this.activePageTitle = title;
      });
  }

}
Rahul dev
  • 1,267
  • 3
  • 18
  • 31

1 Answers1

3
  1. Don't add the service in the @Component.providers. This will cause each component to get its own instance. Instead just put it in the @NgModule.providers of the AppModule. This will make it a singleton.

  2. Use a BehaviorSubject in your service instead of a vanilla Subject if you want the value cached. See further Angular 2 special Observables (Subject / Behaviour subject / ReplaySubject)

Community
  • 1
  • 1
Paul Samsotha
  • 205,037
  • 37
  • 486
  • 720