【问题标题】:Angular subscription and observable repeatedly get dataAngular 订阅和 observable 重复获取数据
【发布时间】:2019-09-20 11:09:49
【问题描述】:

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

这是我的代码

这是我的 inventory.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();
  }

这是我的 inventory.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 中插入一些重复的数组

谁能解释这是为什么?

【问题讨论】:

    标签: angular observable httprequest subscription angular-http


    【解决方案1】:

    首先会返回 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;
          })
        );
    }
    

    然后只需将 1 个请求插入到 x 次调用 api

    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 个条目。

    【讨论】:

    • 我通过一遍又一遍地调用那个 api 来获得分页......互联网很慢所以我需要先调用它来处理 10 个项目......然后再次调用它来添加另外 10 个......我的 mongo 查询是 skip(0).limit(10) 然后当我再次调用 api 然后它的 skip(10).limit(10)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-02
    • 2020-06-19
    • 1970-01-01
    • 2018-12-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多