问题描述
我有两个组件 panelComponent(parent) 和dashboardComponent(child).panelComponent 在其 ngOninit 中订阅了一项服务,其返回值在子组件 ngOninit 中使用.
I have two component panelComponent(parent) and dashboardComponent(child).The panelComponent has a subscription to a service in its ngOninit and its return value is used inside childcomponent ngOninit.
问题是,在Parents服务返回一个值之前,我的孩子的ngOninit在初始运行时执行,我在子组件中得到一个空结果.如何解决这个问题?
The Problem is, on initial running my childs ngOninit executing before Parents service returns a value and I am getting a null result in child component.How to solve this issue?
panelComponent.ts:-
panelComponent.ts:-
ngOnInit() {
this.panelService.getUserProfile().subscribe(
res => {
this.panelService.userDetails = res;
this.router.navigate(['panel/dashboard'])
},
err => {
console.log(err);
},
);
}
panelService.ts:-
panelService.ts:-
export class PanelService {
userDetails;
constructor(private http: HttpClient) {
}
getUserProfile() {
const httpOptions = {
headers: new HttpHeaders({
'Authorization': `Bearer ${localStorage.getItem('token')}`
})
};
return this.http.get('/api/UserProfile/UserProfile', httpOptions);
}
dashboardComponent.ts:-
dashboardComponent.ts:-
ngOnInit() {
console.log(this.panelService.userDetails)
}
推荐答案
这是因为异步调用.有关此检查的更多信息,请在此处正确使用 Angular 5 的异步调用.
在您的情况下它应该可以正常工作,最好在将其重定向到子组件之前检查您从服务获得的响应.
ngOnInit() {
this.panelService.getUserProfile().subscribe(
res => {
if(res) {
this.panelService.userDetails = res;
this.router.navigate(['panel/dashboard'])
}
},
err => {
console.log(err);
});
}
这篇关于在父组件中完成服务之前执行的子组件的 ngOninit的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!