@H_404_6@
我需要在标题中显示路由组件的标题.但是当我在我的应用程序中使用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'); } }
解决方法
尝试使用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 |异步}}