我从另一个组件更新角度组件变量时有一个奇怪的行为。有人可以告诉我为什么会发生这种情况或者我做错了什么?
我有两个组件header.component和home.component在home.component的ngOnInit上我调用api并将该响应共享到header.component以更新header.component.html的值
home.component.ts
@Component({
selector: 'app-home-page',
templateUrl: 'home.component.html',
providers: [ProfileService,HeaderComponent]
})
export class HomeComponent implements OnInit {
constructor(
private _profileService: ProfileService,
private demo:HeaderComponent) {
}
ngOnInit() {
this._profileService.getHomeData()
.subscribe(response => {
this.homeData = {
this.headerComponent.setData(response.json().payload.Profile)
},
err => {
alert('home data error');
});
}
header.component.ts
@Component({
selector: "app-layout-header",
providers: [],
templateUrl: "./header.component.html"
})
export class HeaderComponent implements OnInit {
profile={Name:'demo'};
constructor() {
}
ngOnInit() {
var curr=this
setInterval(function() {
console.log(curr.profile)
},3000)
}
ngOnDestroy() {
}
logout() {
console.log(this.profile)
}
loadHomeData() {}
setData(data) {
console.log(this.profile)
this.profile=data
console.log(this.profile)
}
}
预计在profile
变量上有新值,但在退出点击时我可以看到该值是旧值。
答案 0 :(得分:1)
我的解决方案将从RootComponent传递对HeaderComponent的引用' 包含HeaderComponent和HomeComponent的我将不会使HeaderComponent注入
<强> RootComponent.html 强>
<app-header #header></app-header>
<app-home [headerComponent]="header"></app-home>
<强> HomeComponent.ts 强>
export class HomeComponent {
@Input() headerComponent: headerComponent;
...
}
之后从任何提供者中删除任何组件