Sai chaitanya
Sai chaitanya

Reputation: 87

How to reload the header component when the variable value changes via service?

I need to display the title of the routing component in the header. But when I am using ngOnInit in my app, it is getting the default value. It is not changing even after the variable value is changed via service. How to do that?

Data.service.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable()

export class DataService {

  public myGlobalVar : string = "Chaitanya";

  constructor() { }

  setMyGV(val : string){
    this.myGlobalVar = val;
    console.log(this.myGlobalVar);
  }

  getMyGV(){
    return this.myGlobalVar;
  }
}

header.component.ts

    import { Component, OnInit } from '@angular/core';
    import { DataService } from 'src/app/data.service';

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

      public title : string = '';

      constructor(private _emp : DataService) { }

      ngOnInit() {
        this.title = this._emp.getMyGV();    
      }
}

contact.component.ts

import { Component, OnInit } from '@angular/core';
import { DataService } from 'src/app/data.service';

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

  constructor(private _emp : DataService) { }

  ngOnInit() {
      this._emp.setMyGV('Contact');
      }
}

Before : Before After : After

Upvotes: 5

Views: 2051

Answers (2)

user2900572
user2900572

Reputation: 621

We can directly use service variable in header component and it works.

{{ dataService.myGlobalVar }}

Also no need to of getter and setter since its public variable, we can directly uses it.

Upvotes: 0

Shashank Vivek
Shashank Vivek

Reputation: 17514

Try with BehaviorSubject and NOT just Subject

service.ts

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

@Injectable()

export class DataService {

  public myGlobalVar$ = new BehaviorSubject<string>("Chaitanya");

  constructor() { }

  setMyGV(val : string){
    this.myGlobalVar.next(val);
  }

  getMyGV(){
    return this.myGlobalVar$.asObservable();
  }
}

in header.component

import { Component, OnInit } from '@angular/core';
import { DataService } from 'src/app/data.service';
import { Observable } from 'rxjs';

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

  public title : Observable<string>;

  constructor(private _emp : DataService) { }

  ngOnInit() {
    this.title = this._emp.getMyGV();    
  }

}

in html:

{{ title | async}}

Upvotes: 5

Related Questions