【发布时间】:2019-06-25 20:31:30
【问题描述】:
我需要在标题中显示路由组件的标题。但是当我在我的应用程序中使用 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');
}
}
【问题讨论】:
-
它没有改变,因为你在
onInit中有代码 -
标题组件已经正确加载,所以它如何检测标题的变化。在标头组件中将
_emp公开,并在html 中用作_emp.myGlobalVar。 -
尝试在标题组件中使用 onChanges。我认为它会起作用。
-
@AndréPacheco : 如果是
@Input就可以了 :) -
Onchanes 不工作
标签: angular