【问题标题】:Angular- Wait until subscribes returns valueAngular-等到订阅返回值
【发布时间】:2021-07-16 09:55:13
【问题描述】:

在我的 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 文件加载内容。

【问题讨论】:

  • 请显示整个代码。如果这是在 if-else 中,则重新构建整个 observable 以有条件地返回会更容易,而不是在 if-block 中订阅。
  • 您可以使用嵌套订阅,也可以在您的代码中使用 async-await,请分享整个代码,直到我们找到好的解决方案
  • 您似乎删除了对 if-else 语句的任何提及。作为一般规则,任何依赖于带有 observable 的异步数据的语句都必须在订阅中。
  • 我已将该语句保留在订阅中,但我想要的是,在我的文件加载到 MsgHandler 之前,应该暂停进一步的代码执行

标签: angular async-await promise observable


【解决方案1】:

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

在 Angular 生命周期中,组件构造函数将在应用程序挂载之前被调用。

【讨论】:

  • 但我想先加载这个文件
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-09-11
  • 2021-04-27
  • 2022-09-23
  • 2017-07-14
  • 1970-01-01
  • 1970-01-01
  • 2019-12-09
相关资源
最近更新 更多