Angular 5在页面激活服务后执行功能



我的 Angular 项目中有多个服务和页面。

Pages:
1) Login
2) Dashboard
3) Order List
Services:
1) UserService
2) OrderService

访问订单列表页面的正确过程是:

1( 登录 -userServices初始化

2( 系统将用户重定向到仪表板 - 在调用内部函数之前初始化OrderService

3(用户转到订单列表 -OrderService内部的函数已准备好从OrderList > ngOnInit()执行该函数

我有一个问题是,如果用户直接进入http://localhost:4200/orderList页面而不经过进程1和2,则OrderService尚未初始化,因此从OrderListPage调用ngOnInit()中的函数时,它将遇到错误"Cannot read property 'child' of undefined"

我的order.service.ts

currentUser
iwoRef
constructor() {
firebase.auth().onAuthStateChanged(user => {
if (user) {
this.currentUser = user;
this.iwoRef = firebase.database().ref(`/iwo`);
console.log('order services loaded')
}
else{
return false
}
});
}
getIwo(iwo){
return this.iwoRef.child('stock')
}

我的order-list.component.ts

constructor(private orderService: OrderService) {  }
ngOnInit() {
this.orderService.getIwo().on('value',snap>{
console.log(snap.val())
})
}

我的错误序列显示在 chrome 控制台中:

> Cannot read property 'child' of undefined --order.service.ts
> order services loaded --order.service.ts

如果用户通过流程 1、2、3,则不会出现上述问题,我怀疑是因为订单服务已在 DashboardPage 中完全初始化。

我确实尝试在订单列表页面中使用其他角度生命周期函数来执行this.orderService.getIwo()但它没有按预期工作:

ngDoCheck, ngAfterContentInit,ngAfterContentChecked, ngAfterViewInit, ngAfterViewChecked

请指教。

谢谢!

你需要初始化 iwoRef 吗

this.iwoRef = firebase.database().ref(`/iwo`);

关于身份验证更改?

如果没有,则将其移出

onAuthStateChanged

它将在不更改身份验证的情况下进行初始化。

最新更新