2

Im having some trouble figuring this out, basically I have a headerTitleService which I want to be able to dynamically set the title in my header component but for some reason when I set the title nothing shows up? Im not getting any errors so I can seem to figure out what the problem is..

headerTitle.service.ts

import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';

@Injectable()
export class HeaderTitleService {
  title = new BehaviorSubject('');

  constructor() { }

  setTitle(title: string) {
    this.title.next(title);
  }
}

header.component.ts

import { Component, OnInit } from '@angular/core';
import { HeaderTitleService } from '../../../services/headerTitle.service'

@Component({
  selector: 'app-header',
  templateUrl: './header.component.html',
  styleUrls: ['./header.component.scss'],
  providers: [HeaderTitleService]
})
export class HeaderComponent implements OnInit {
  title: string;

  constructor(
    private headerTitleService: HeaderTitleService
  ) { }

  ngOnInit() {
    this.headerTitleService.title.subscribe(updatedTitle => {
      this.title = updatedTitle;
    });
  }

}

header.component.html

<h1>{{title}}</h1>

home.component.ts

import { Component, OnInit } from '@angular/core';
import { HeaderTitleService } from '../../services/headerTitle.service';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.scss'],
  providers: [HeaderTitleService]
})
export class HomeComponent implements OnInit {

  constructor(
    private headerTitleService: HeaderTitleService
  ) { }

  ngOnInit() {
    this.headerTitleService.setTitle('hello');
  }

}
Jota.Toledo
  • 27,293
  • 11
  • 59
  • 73
Smokey Dawson
  • 8,827
  • 19
  • 77
  • 152
  • Possible duplicate of [Share data between components using a service in Angular2](https://stackoverflow.com/questions/42567674/share-data-between-components-using-a-service-in-angular2) – Jota.Toledo Dec 07 '17 at 23:19

2 Answers2

4

The line providers: [HeaderTitleService] in each component means that they will be given one HeaderTitleService each, rather than one between them.

To fix this remove providers: [HeaderTitleService] from your components, and place it in your module definition instead:

@NgModule({
  providers: [HeaderTitleService]
})
UncleDave
  • 6,872
  • 1
  • 26
  • 44
3

Move HeaderTitleService in providers of your module. With your implementation you receive new instance of the HeaderTitleService in each component.

Hope this helps.

Nikola Yankov
  • 1,264
  • 1
  • 15
  • 28