【发布时间】:2018-11-12 17:35:36
【问题描述】:
在我的app.component.ts 中,我正在进行 API 调用并获取 userDetails。然后我发出这个userDetails。我在我的header 组件中订阅了这个userDetails。我的标头组件使用app-my-image-logo 组件。在页面刷新时,调用 API 并获取 userDetails。之后,事件被发出,因此,testnDisplay 方法被调用。但我的问题是每隔几秒钟,我就会在控制台上得到以下输出。
img my-image-logo.component.ts:28
name my-image-logo.component.ts:28
img my-image-logo.component.ts:28
name my-image-logo.component.ts:28
img my-image-logo.component.ts:28
name my-image-logo.component.ts:28
img my-image-logo.component.ts:28
name my-image-logo.component.ts:28
所以,这个方法在频繁的间隔后被多次调用,但它应该只被调用一次。
header.component.html
<app-my-image-logo ></app-my-image-logo>
header.component.ts
ngOnInit() {
const self = this;
this.userDetails = this.dataService.getUserDetails();
this.dataService.userDetailsEvt.subscribe(
function(data){
self.userDetails = data;
}
);
}
这是app-my-logo 组件。
app-logo.component.html
<img #imgDiv [hidden]="testnDisplay('img')" >
<div [hidden]="testnDisplay('name')"
></div>
app-logo.component.ts
testnDisplay(type){
console.log(type);
}
这是我的dataService:
data.service.ts
setUserDetails(userDetails){
this.userDetails = userDetails;
this.userDetailsEvt.emit(this.userDetails);
}
getUserDetails(){
return this.userDetails;
}
app.component.ts
this.authService.httpPost("/auth/getUserDetails", payload).subscribe(
function (data: any) {
self.dataService.setUserDetails(data);
},
function(error){
}
);
【问题讨论】:
标签: angular