Angular订阅和可观察的反复获取数据

时间:2019-09-20 11:09:49

标签: angular observable httprequest subscription angular-http

我在使用订阅和可观察性时遇到问题

这是我的代码

这是我的stock.service.ts

getInventoryList = (page: string,pageSize,size) => {
    const userLocation = this.authService.getUserLocation();
    let queryParams = `?page=${page}&loc=${userLocation}&size=${size}&pageSize=${pageSize}`;
      this.http
      .get<{ success: boolean, message: string, inventoryList: any }>(BACKEND_URL_item + '/getInventoryList' + queryParams)
      .pipe(retry(3), catchError((data) => {
        return EMPTY;
      }),map((data) => {
        if (page === 'inventory') {
          return {
            extractedInventoryList: data.inventoryList.map((item: any) => {
              return {
                itemId: item._id,
                itemID: item.itemID,
                itemName: item.itemName,
                itemSellingPrice: item.itemSellingPrice,
                itemPurchasePrice: item.itemPurchasePrice,
                itemAveragePurchasePrice: item.itemAveragePurchasePrice,
                itemBaseUnit: item.itemBaseUnit,
                itemCategory: item.itemCategory,
                itemReorderPoint: item.itemReorderPoint,
                itemTotalQuantity: item.itemTotalQuantity,
                itemSumQuantity: item.itemSumQuantity,
                itemLocation: item.itemLocation,
                itemSubLocation: item.itemSubLocation
              };
            }),
            success: data.success,
            message: data.message
          };
        } else {
          return {
            extractedInventoryList: data.inventoryList.map((item: any) => {
              return {
                itemId: item._id,
                itemName: item.itemName,
                itemTotalQuantity: item.itemTotalQuantity,
                itemLocation: item.itemLocation,
                itemSubLocation: item.itemSubLocation
              };
            }),
            success: data.success,
            message: data.message
          };
        }
      }))
      .subscribe((transformedData) => {
          this.inventoryList = transformedData.extractedInventoryList;
          this.inventoryListObserver.next({
            inventoryList: [...this.inventoryList],
            success: transformedData.success,
            message: transformedData.message
          });

        }
      });

  }

  getInventoryListListener = () => {
    return this.inventoryListObserver.asObservable();
  }

这是我的stock.component.ts

getInventoryItem(pageSize,size) {

    for(let x=0;x<size;x= x+10){

          this.inventoryService.getInventoryList('inventory',pageSize,x);
          this.itemListSubscription = this.inventoryService
        .getInventoryListListener()
        .subscribe((responseData: { inventoryList: IItem[], success: boolean, message: string }) => {
          if (!responseData.success) {
            this.spinner.stop();

          } else {
            this.itemList = this.itemList.concat(responseData.inventoryList);
            this.spinner.stop();
            this.itemListBackup = this.itemList;
          }
           this.showToasts(responseData.message, responseData.success);
        });




    }

  }

我正在尝试每10个项目获取数据。我使用的是mongodb,它返回的正是我想要的内容,但是当我通过Angular获得数据时,它将一些重复的数组插入到itemList

谁能解释为什么?

1 个答案:

答案 0 :(得分:0)

首先将返回http Observable

public getInventoryListo(page: string, pageSize: number, size: number): Observable<any> {
  const userLocation = this.authService.getUserLcation();
  const queryParams = `?page=${page}&loc=${userLocation}&size=${size}&pageSize=${pageSize}`;
  return this.http
    .get<{ success: boolean, message: string, inventoryList: any }>(BACKEND_URL_item + '/getInventoryList' + queryParams)
    .pipe(
      .map((data) => {
        if (page.toLowerCase() === 'inventory') {
          return {
            extractedInventoryList: data.inventoryList.map((item: any) => {
              return {
                itemId: item._id,
                itemID: item.itemID,
                itemName: item.itemName,
                itemSellingPrice: item.itemSellingPrice,
                itemPurchasePrice: item.itemPurchasePrice,
                itemAveragePurchasePrice: item.itemAveragePurchasePrice,
                itemBaseUnit: item.itemBaseUnit,
                itemCategory: item.itemCategory,
                itemReorderPoint: item.itemReorderPoint,
                itemTotalQuantity: item.itemTotalQuantity,
                itemSumQuantity: item.itemSumQuantity,
                itemLocation: item.itemLocation,
                itemSubLocation: item.itemSubLocation
              };
            }),
            success: data.success,
            message: data.message
          };
        } else {
          return {
            extractedInventoryList: data.inventoryList.map((item: any) => {
              return {
                itemId: item._id,
                itemName: item.itemName,
                itemTotalQuantity: item.itemTotalQuantity,
                itemLocation: item.itemLocation,
                itemSubLocation: item.itemSubLocation
              };
            }),
            success: data.success,
            message: data.message
          };
        }
      })
      retry(3), 
      catchError((data) => {
        return EMPTY;
      })
    );
}

然后只需向调用api的x次发出1个请求

getInventoryItem(pageSize: number, maxSize: number): void {
  this.itemList = [];

  for (let i = 0; i < maxSize;  i += 10) {
    this.inventoryService.getInventoryList('inventory', pageSize, x).subscribe((response: any) => {
      this.spinner.stop();
            this.showToasts(responseData.message, responseData.success);

      if (response.success) {
        for (let j of response.inventoryList) this.itemList.push(j);
        this.itemListBackup = this.itemList;
      }
    });
  }
}

此外,如果您使用ngFor在模板中显示列表,则可以使用slice pipe

例如:*ngFor="let item of itemList | slice: 0: 10"这将显示前10个条目。