angular - 继续功能之前的角度等待数据
问题描述
这是我的代码:
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();
}
}
}
推荐阅读
- c++ - 关于将源代码分成多个标头和 cpp 的 C++ 建议
- python - 熊猫数据框图中的系列标记
- javascript - 如何在按钮单击时将网站加载为 iframe 并将参数传递给 Angular 中的 URL
- php - 在 foreach 中格式化 DateTime 的问题
- laravel - Laravel 分解分页的雄辩查询
- bash - 循环将变量分配给文件名的片段,然后在命令中为目录中的每个文件使用
- artifactory - JFrog Artifactory 系统还原失败
- yargs - 将带空格的字符串传递给节点 cli-parser
- java - 如何使用 HttpURLConnection 在 Java 中包含 SOAP 请求的标头信息
- c# - Automapper 和处理空属性