这是我的代码。
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函数?
你可以重新安排代码,使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();
}
}
}