【问题标题】:Wait for the HTTP request to be completed to continue the rest of the script in Angular等待 HTTP 请求完成以继续 Angular 中的其余脚本
【发布时间】:2021-09-25 21:36:00
【问题描述】:

我有一个函数 getData(),它调用 API、处理数据、转换并将其保存到 BehaviorSubject。然后使用 of() 将处理后的数据作为 observable 返回。

getData()

getData(fId: string | null = null) {

    // get the data to tempItems with an API Call
    this.getDataFromAPI().subscribe(data => {
        this.tempItems = [data]
    })

    let items = cloneDeep(this.tempItems);

    // Separate the items by folders and files
    const a: Item[] = items.filter(item => item.type === 'a');
    const b: Item[] = items.filter(item => item.type !== 'b');

    const path: Item[] = [];
    //do some work

    // Create  data

    let data = {
        folders: a,
        files: b,
        path
    }

    // Add this data to the BehaviorSubject
    this._items.next(data);

    return of(data);
}

getDataFromAPI()

    getDataFromAPI() {
    return this._httpClient.get(URL);
}

getData() 函数中,变量this.tempItems 在运行时未定义。由于 HTTP 调用,脚本的其余部分不会等待 HTTP 请求完成。

如何在此处正确使用 Async Await?仍然,设法返回of(data)

调用 getData() 函数的函数期望返回一个 observable

【问题讨论】:

标签: angular typescript async-await observable


【解决方案1】:

您可以使用这样的运算符:

getData(fId: string | null = null) {

    return this.getDataFromAPI().pipe(
        tap(data => {
            this.tempItems = [data]
        }),
        map(data => {
             let items = cloneDeep([data]);

             // Separate the items by folders and files
             const a: Item[] = items.filter(item => item.type === 'a');
             const b: Item[] = items.filter(item => item.type !== 'b');

             const path: Item[] = [];
             //do some work

            // Create  data

            return {
                folders: a,
                files: b,
                path
            };
        }),
        tap(data => {
              this._items.next(data);
        })
    );
}
  • tap 用于应用副作用,不会改变发出的值
  • map 用于转换发射值

【讨论】:

    【解决方案2】:

    在你的 API 函数上使用 async/await 和 promise

     async getDataFromAPI() 
      {
        return   { await  this._httpClient.get(URL).toPromise() }
      }
    

    【讨论】:

      猜你喜欢
      • 2021-06-04
      • 2018-07-19
      • 2017-01-17
      • 1970-01-01
      • 1970-01-01
      • 2020-07-24
      • 1970-01-01
      • 2020-04-15
      • 1970-01-01
      相关资源
      最近更新 更多