通过服务更改变量值时如何重新加载标头组件?

时间:2019-02-01 09:28:31

标签: angular

我需要在标题中显示路由组件的标题。但是,当我在应用程序中使用ngOnInit时,它将获取默认值。即使通过服务更改了变量值,它也没有改变。该怎么做?

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

2 个答案:

答案 0 :(得分:5)

尝试使用BehaviorSubject而不仅仅是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();
  }
}

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

}

html 中:

{{ title | async}}

答案 1 :(得分:0)

我们可以直接在标头组件中使用服务变量,并且它可以正常工作。

{{ dataService.myGlobalVar }}

由于它的公共变量,因此也不需要getter和setter,我们可以直接使用它。