首页 > 解决方案 > 离子 4 选项卡 ionViewWillEnter 在设备 readyReady 事件之前触发

问题描述

我的 app.components.ts 构造函数中有 initializeApp 代码,如下所示:

app.components.ts

constructor(
    private platform: Platform,
    private splashScreen: SplashScreen,
    private statusBar: StatusBar,

    ) {
    this.initializeApp();
  }

initializeApp() {

    this.platform.ready().then(async() => {

      this.statusBar.styleDefault();

       //set device info
       this.core.deviceId = this.device.uuid
       console.log("Device id is::" + this.core.deviceId)
}

我有选项卡布局,其中 tab1 显示为默认值。此选项卡具有使用上述设备 ID 的 ionViewWillEnter 方法。问题是 tab1.ts 在 deviceReady 被触发之前被调用。

将 tab1.ts 中的触发推迟到设备就绪被触发和初始化的解决方案是什么?

tab1.ts

  ionViewWillEnter(){
    console.log("got in with id:" + this.core.getUserKey())
    this.core.refreshData()
  }

标签: angularcordovaionic-frameworkeventsionic4

解决方案


只要在 app.component 中设置了 deviceId,您就可以使用 observable 来访问它。

核心服务.ts

public deviceId: Subject<string> = new BehaviorSubject<string>(null);

broadcastDeviceId(deviceId:string) {
   this.deviceId.next(deviceId);
}
getDeviceId(): Observable<any> {
   return this.deviceId.asObservable();
}

app.component.ts

 initializeApp() {
     this.platform.ready().then(async() => {
        //set device info
        this.core.broadcastDeviceId(this.device.uuid)
     })
 }

tab1.ts

ionViewWillEnter(){
    console.log("got in with id:" + this.core.getUserKey())
    this.core.getDeviceId().subscribe(deviceId:string)=>{
     console.log(deviecId)
    })
}

推荐阅读