angular - Angular-等到订阅返回值
问题描述
在我的 app.component.ts 中,我在构造函数中有代码来获取 json 文件,然后将其数据解析为一个变量,该变量进一步传递给消息模块。
这是我的 Jsonreadservice.ts。
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { Injectable } from '@angular/core';
@Injectable()
export class JsonReadService {
constructor(private http: HttpClient) {}
public getJSON(filepath): Observable<any> {
return this.http.get(filepath);
}
}
此外,这是我的 app.component.ts 的构造函数中的代码,其中 MsgModule 将文件数据作为第二个参数的输入。
jsonFile:string;
constructor( private jsonread: JsonReadService) {
this.jsonread.getJSON(this.filepath).subscribe(data => { this.jsonFile=data;
MsgHandler.MsgModule(ModuleName, this.jsonFile); });
}
我需要等待继续执行,直到我的消息处理程序没有从 json 文件加载内容。
解决方案
将你的函数从构造函数移到 ngOninit() 上。
在角度生命周期中,将在安装应用程序之前调用组件构造函数。
推荐阅读
- crc - 我应该如何为 HDLC 实施 CRC?(CRC16-CCITT)
- javascript - 无法为 Material UI 中的选项卡应用水平滚动
- reactjs - 如何访问 mapstatetoprops 方法中的本地状态
- angular - 分配一个方法来动态点击
- api-platform.com - API Platform GraphQL 为相关实体创建具有实体特定连接的通用类型 IterableConnection
- javascript - Axios/Express 之间的数据丢失
- javascript - TypeError:Undefined is not an object 在 ReactNative 中尝试动画时
- mongodb - 在 mongodb 中的每个文档的数组中查找重复项
- typescript - 使用组合 api 和 typescript 类型系统强类型化 vue 组件的 props
- python - Visual Studio Code 和 PowerShell 无法识别新的 Python 版本