首页 > 解决方案 > 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 文件加载内容。

标签: angularasync-awaitpromiseobservable

解决方案


将你的函数从构造函数移到 ngOninit() 上。

在角度生命周期中,将在安装应用程序之前调用组件构造函数。


推荐阅读