Smokey Dawson
Smokey Dawson

Reputation: 9230

shared information between components through service not working

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

}

Upvotes: 2

Views: 50

Answers (2)

Nikola Yankov
Nikola Yankov

Reputation: 1304

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

Hope this helps.

Upvotes: 3

UncleDave
UncleDave

Reputation: 7188

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

Upvotes: 4

Related Questions