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 : 
After : 
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}}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With