继续功能之前的角度等待数据



这是我的代码:

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(event)方法中发出HTTP请求。尝试以下

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();
}
}
}

最新更新