我需要在标题中显示路由组件的标题。但是,当我在应用程序中使用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');
}
}
答案 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,我们可以直接使用它。