【问题标题】:Angular wait for subscribe to finishAngular等待订阅完成
【发布时间】:2019-03-24 15:25:07
【问题描述】:

我正在尝试使用 Angular 实现一个测试应用程序。问题场景是我需要执行 Get 并根据从该 Get 请求中获得的数据返回一个值。见下文:

public getNextId(entityName: string): number {
    console.info('Retrieving next ID for  ' + entityName);

    let seqId: SeqId;

    const url = `${this.apiURL}/${entityName}`;

    console.info('SeqID URL: ' + url);

    this.http.get<SeqId>(url)
        .subscribe((data: SeqId) => seqId = data); -> 1

    /*Do something with seqId */ -> 2

    return seqId.nextEntityId;
}

问题是 (2) 在 (1) 之前执行。当达到 (2) 时,seqId 变量尚未设置。

如何使用相同的方法进行 Get、处理检索到的数据并返回某些内容?

提前致谢

【问题讨论】:

标签: angular typescript observable httpclient subscribe


【解决方案1】:

你需要从这里返回一个 observable 而不是订阅

  GetData() {return  this.http.get<SeqId>(url)
    .pipe(map(data: SeqId) => seqId = data); 
}

并在控制器中,订阅此方法并进行所需的操作

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-04-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多