我需要在标题中显示路由组件的标题.但是当我在我的应用程序中使用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;
}
}
Run Code Online (Sandbox Code Playgroud)
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();
}
}
Run Code Online (Sandbox Code Playgroud)
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');
}
}
Run Code Online (Sandbox Code Playgroud)
尝试BehaviorSubject而不仅仅是Subject
服务
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();
}
}
Run Code Online (Sandbox Code Playgroud)
在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();
}
Run Code Online (Sandbox Code Playgroud)
}
在html中:
{{ title | async}}
| 归档时间: |
|
| 查看次数: |
63 次 |
| 最近记录: |