首页 > 解决方案 > 继续功能之前的角度等待数据

问题描述

这是我的代码:

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函数?

标签: angularasynchronous

解决方案


您可以重新排列代码以在方法内发出 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();
    }
  }
}

推荐阅读