簡體   English   中英

如何在角度使異步功能?

[英]How to make asynchronous function in angular?

componentOne.ts中,我通過sharedService發送數據,

  this.sharedService.sendData(this.getCheckedProduct);

componentTwo.ts中,我正在訂閱數據,例如,

      productList: any = [];

      getAllProducts: any = [];

      ngOnInit() {
        this.sharedService.getData().subscribe(data => {
          this.productList = data;
          this.getProduct();
        });
      }

我在productlist中獲取數據,然后需要調用具有以下內容的函數this.getProduct()

  getProduct() {
    let tempArray = [];
    this.productList.forEach(element => {
        this.appService.getRest(AppConfig.settings.product.getProducts + '/' + element.product_obj_id).subscribe(res => {
          tempArray.push(res.data);
        });
    });
    this.getAllProducts = tempArray;
  }

我需要傳遞ID element.product_obj_id以獲得該ID的必要數據。

試圖像這樣改變以上情況,

  ngOnInit() {
    this.sharedService.getData().subscribe(data => {
      data.forEach(element => {
        this.getProduct(element);
      })
    });
  }

  async  getProduct(element) {
    let asyncResult = await this.appService.getRest(AppConfig.settings.product.getProducts + '/' + element.product_obj_id).toPromise();
    this.getAllProducts.push(asyncResult['data']);
  }

我在async getProduct(element)函數內部,獲取this.getAllProducts的數據,但是在html中,我沒有獲取數據。

HTML:

<div *ngFor="let product of getAllProducts">
 Getting data
</div>

如果我用異步更改了以上內容

<div *ngFor="let product of getAllProducts | async">
 Getting data
</div>

我收到錯誤消息,

ERROR Error: InvalidPipeArgument: '' for pipe 'AsyncPipe'
    at invalidPipeArgumentError

為了詳細解釋,我需要通過componentone中的sharedservice發送數據並在componenttwo中接收它,然后需要從該共享服務數據中獲取product_obj_id

傳遞每個id時,我將獲取該特定產品的數據,並且我需要存儲從this.appService.getRest(AppConfig.settings.product.getProducts + '/' + element.product_obj_id).toPromise(); getAllProducts ..

AppConfig.settings.product.getProducts 

網址是..

如何以異步方式實現它。到目前為止,我正在獲取數據

this.getAllProducts.push(asyncResult['data']);

但是在函數之外,我沒有得到值,而且getAllProducts不再在html中的任何情況下工作。

在此問題頂部解釋的方案1中 ,我給出了以下內容

this.getAllProducts = tempArray;

這給空數組作為值,所以只有我正在嘗試async功能。

簡單來說,我需要從this.getAllProducts獲取最終數據,該數據將通過get方法從service接收,為此我需要在url中傳遞ID。

只需像這樣在異步調用中分配數據-

getProduct() {
    let tempArray = [];
    this.productList.forEach(element => {
        this.appService.getRest(AppConfig.settings.product.getProducts + '/' + element.product_obj_id).subscribe(res => {
          tempArray.push(res.data);
          this.getAllProducts = tempArray; // Here
        });
    });
  }

PS:在您的用例中,無需使用管道async

AsyncPipe將應用於Observable 就您而言,您將其應用於getAllProducts ,它是一個Array ,我相信。 因此,您將收到該錯誤。

可能的解決方案:

  1. getAllProducts的for循環中刪除async
  2. 使getAllProducts返回Observable到的產品

注意:由於要遍歷productList並調用webapi來獲取產品,因此可能必須使用mergeMap

解決方案2樣本:

我相信,解決方案2是最適合你,因為你productList包含了所有你需要打的WebAPI,以獲得產品的詳細情況的產品

在此處了解MergeMap

示例代碼(未經測試,您需要添加代碼以使用catchError處理錯誤):

import { from } from 'rxjs';
import { mergeMap, map, combineAll } from 'rxjs/operators';

this.getAllProducts = from(this.productList)
    .pipe( 
        mergeMap(element =>
            this.appService.getRest(AppConfig.settings.product.getProducts + '/' + element.product_obj_id).pipe(
                map(res => res['data'])
            )
        ),
        combineAll()
    )

<div *ngFor="let product of getAllProducts | async">
    Getting data
</div

說明:

因為您的productList是一個Array ,所以您必須遍歷它並向該Array每個product對象觸發請求

from(this.productList)使得在每個對象productList成可觀察到的。 我們添加一個pipe ,並使用mergeMap我們可以解雇為每個請求product ,因此你看到this.appService.getRest(AppConfig.settings.product.getProducts + '/' + element.product_obj_id)這里面mergeMap 然后,我們map從webapi獲得的response ,並僅使用res['data']返回數據。 最后,我們combineAll所有返回Observable<[]>的響應,並將其設置為getAllProducts ,因此getAllProducts是一個Observable ,我們可以在其上使用AsyncPipe

編輯:

constructor而不是ngOnit添加以下ngOnit

const getAllProducts = this.sharedService.getData().pipe(
  mergeMap(data=> from(data))
).pipe( 
    mergeMap(element =>
        this.appService.getRest(AppConfig.settings.product.getProducts + '/' + element.product_obj_id).pipe(
            map(res => res['data'])
        )
    ),
    combineAll()
)

暫無
暫無

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

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