继续函数前的Angular等待数据

问题描述 投票:0回答:1

这是我的代码。

App-component.html

<router-outlet (activate)="onActivate($event)"></router-outlet>
App-component.ts

node;
ngOnInit() {
  this.loadData();
}
loadData() {
  return service.getData().subscribe(res => this.node = res)
}
onActivate(event) {
  // wait node get data then continue this function

}

2个函数同时运行,有没有办法等节点从loadData()获得数据后再继续onActivate函数?

angular asynchronous
1个回答
0
投票

你可以重新安排代码,使HTTP请求位于 onActivate(event) 方法。试试下面的方法

import { Component, OnInit, OnDestroy } from '@angular/core';

import { Subject, Observable, Subscription } from 'rxjs';

export class AppComponent implements OnInit, OnDestroy {
  node: any;
  subscription: Subscription;

  ngOnInit() {
    // don't trigger the HTTP call here
  }

  loadData(): Observable<boolean> {
    const result = new Subject<boolean>();

    this.service.getData().subscribe(
      res => {
        this.node = res;
        result.next(true);
      },
      error => { 
        // handle error
        result.next(false);
      } 
    );

    return result;
  }

  onActivate(event) {
    // wait node get data then continue this function
    this.subscription = this.loadData().subscribe(
      status => {
        if (status) {
          // proceed further
        }
      }
    );
  }

  ngOnDestroy() {
    if (this.subscription) {
      this.subscription.unsubscribe();
    }
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.