Angular 2 Component communication by service not working -
i trying communicate between 2 components service it's not working me, , don't understand why. please guide me through this. want change page title bar when change page.
service
import {injectable} '@angular/core'; import {subject} '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} '@angular/core'; import {updatepagetitleservice} '../../../../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} '@angular/core'; import {updatepagetitleservice} '../../../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; }); } }
don't add service in
@component.providers
. cause each component own instance. instead put in@ngmodule.providers
ofappmodule
. make singleton.use
behaviorsubject
in service instead of vanillasubject
if want value cached. see further angular 2 special observables (subject / behaviour subject / replaysubject)
Comments
Post a Comment