簡體   English   中英

在 typescript 中正確使用異步(角度)

[英]use async properly in typescript (angular)

我有一個部門列表,將從 API 鏈接中獲取。

當我的 angular 應用程序加載時(我的意思是在ngOnInit(): void調用之后),我想要:

  1. 我將async獲取所有部門
  2. 然后我將await所有部門加載
  3. 最后,我將第一個部門的 ID 保存在一個變量中

我很困惑我應該把我的等待

(注意:我的代碼正在運行,API 響應來找我,我只卡在等待部分)

這是我嘗試了多遠:

app.component.ts:

import { Component, OnInit } from '@angular/core';
import { DepartmentModel } from '../../user/models/individual-department.model';

@Component({
  selector: 'app-requisition-report-one',
  templateUrl: './requisition-report-one.component.html',
  styleUrls: ['./requisition-report-one.component.css']
})
export class RequisitionReportOneComponent implements OnInit {

  displayIndividualDepartmentList: DepartmentModel[] = [];

  currentDisplayDepartment: number = null;


  constructor(private userService: UserService) { }

  ngOnInit(): void {
    this.initializeDepartmentList();
  }


  initializeDepartmentList() {
    this.userService.GetAllIndividualDepartment().subscribe(
      async (data: DepartmentModel[]) => {
        this.displayIndividualDepartmentList = data;
        this.currentDisplayDepartment = await this.displayIndividualDepartmentList[0].department_id;
      }
    );
  }

  onShowButtonClick() {
    console.log(this.currentDisplayDepartment);
  }

}

我的 vscode 給了我這樣的警告

'await' has no effect on the type of this expression.ts(80007)

此外,在顯示按鈕單擊時,我得到 null 值。

await要加載的列表之后,我想從列表displayIndividualDepartmentList中獲取此變量currentDisplayDepartment中的第一個部門的 id。

TIA

RxJS observables不依賴於異步/等待功能,而是依賴於訂閱/回調模式。 您的回調 function 將在UserServiceGetAllIndividualDepartment方法返回的可觀察對象發出新值時執行,因此不需要任何異步前綴。 您可以以同步方式訪問數據,而無需使用 await 關鍵字。

 initializeDepartmentList() {
    this.userService.GetAllIndividualDepartment().subscribe(
      (data: DepartmentModel[]) => {
        this.displayIndividualDepartmentList = data;
        this.currentDisplayDepartment = this.displayIndividualDepartmentList[0].department_id;
      }
    );
  }

RxJS observables 的快速解釋以及它們與您習慣使用的Promise的不同之處。

您可以將 Observable 轉換為 promise,如下所示,並使用 async/await 語法而不是 .then() 語法。

toPromise() 方法將為您處理訂閱/取消訂閱,並且僅在可觀察對象完成時發出。 在 HTTP observables 的情況下,它們通常只發出一個值(原始值或其他值)然后完成。

然后,您可以使用所示的 async/await 語法或 use.then()。

將 toPromise() 與 HTTP 可觀察對象一起使用是一種非常引人注目且簡潔的語法,使異步代碼看起來同步且更易於遵循。

  async initializeDepartmentList(): Promise<void> {
    const data: DepartmentModel[] = await this.userService.GetAllIndividualDepartment().toPromise();
    this.displayIndividualDepartmentList = data;
    this.currentDisplayDepartment = this.displayIndividualDepartmentList[0].department_id;
  }

像這樣打電話...

async ngOnInit(): Promise<void> {

    await this.initializeDepartmentList();
.
.
}

或者像這樣使用自調用 function 。


ngOnInit()
{
(async () => {
  await this.initializeDepartmentList();
})()
}

只是補充一點,在 RxJS 7 中不推薦使用 toPromise,並將在 RxJS 8 中刪除。

取而代之的是你可以使用lastValueFrom

const data = await lastValueFrom(this.userService.GetAllIndividualDepartment());

作為旁注,如果您想在啟動時初始化您的應用程序,您可以使用...

app.module.ts

providers: [
    {
      provide: APP_INITIALIZER,
      useFactory: appInitializeService,
      multi: true
    },

像這樣的東西。 promise 返回無效。 該應用程序在繼續之前有效地等待您的先決條件加載。

export const appInitializeService = (): () => Promise<void> => (): Promise<void> => new Promise((resolve) => resolve());

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM