Angularjs   发布时间:2022-04-20  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了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');
      }
}

之前:

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


之后:

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

解决方法

尝试使用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$;
  }
}

在header.component中

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

@Component({
  selector: 'app-header',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 |异步}}

大佬总结

以上是大佬教程为你收集整理的angular – 当变量值通过服务更改时如何重新加载标头组件?全部内容,希望文章能够帮你解决angular – 当变量值通过服务更改时如何重新加载标头组件?所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签: