【问题标题】:Wait for an event before load a ionic3 deeplinked page在加载 ionic3 深层链接页面之前等待事件
【发布时间】:2017-10-01 17:46:46
【问题描述】:

我有一个 Ionic3/Angular4 应用程序,数据来源取决于当前登录的用户,所以我必须等待用户数据事件被触发才能设置数据连接。 (我使用 firebase 来管理用户身份验证)。

在主要组件中我有这个:

  async ngOnInit() {
    this.afAuth.authState.subscribe(async data => {
      if (data && !data.isAnonymous) {    
        await this.userService.initSettingsAsync(data.uid);
      }
      else {
        this.nav.setRoot('LoginPage');
      }
    });
  }

我的页面是这样的:

@IonicPage({
  segment: 'customers/:customerId',
  defaultHistory: ['CustomersPage'],
})
@Component({
  selector: 'page-customer-detail',
  templateUrl: 'customer-detail.html',
})
export class CustomerDetailPage {
  customerId: string;
  customer: Customer;

  constructor(public navParams: NavParams, private customerService: CustomerService) {
    this.customerId = navParams.get("customerId");
  }

  async ionViewDidLoad() {
    console.log('ionViewDidLoad CustomerDetailPage');
    this.customer = await this.customerService.get(this.customerId);
  }
}

this.customerService.get(this.customerId) 必须在this.userService.initSettingsAsync(data.uid) promise 得到解决后执行,否则 userService 不知道从哪里获取数据。

当页面通过深度链接加载时,它会在 authState 事件触发之前进行初始化。

我怎样才能巧妙地处理这个问题?我的意思是,我不喜欢将用户资料放在需要数据的每个页面上。

【问题讨论】:

    标签: angular ionic3


    【解决方案1】:

    在初始化完成后添加 ion-nav 就足够了。超级简单;) 希望对您有所帮助。

    app.html:

    <ion-nav *ngIf="initialized" [root]="rootPage" #content></ion-nav>
    

    app.component.ts:

      async ngOnInit() {
        this.afAuth.authState.subscribe(async data => {
          if (data && !data.isAnonymous) {    
            await this.userService.initSettingsAsync(data.uid);
            this.initialized = true;
          }
          else {
            this.initialized = true;
            setTimeout(() => this.openPage('LoginPage'));
          }
        });
      }
    

    因为 'nav' 是在初始化之后添加到视图中的,所以需要一个小技巧(Angular 2 @ViewChild in *ngIf):

      private nav: Nav;
      @ViewChild(Nav) set contnav(nav: Nav) {
        this.nav = nav;
      }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多