Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

angular

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

like image 581
Sai chaitanya Avatar asked Feb 01 '19 09:02

Sai chaitanya


1 Answers

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

like image 91
Shashank Vivek Avatar answered Sep 29 '22 23:09

Shashank Vivek