代码之家  ›  专栏  ›  技术社区  ›  Maniraj Murugan

如何在角度上实现异步函数?

  •  0
  • Maniraj Murugan  · 技术社区  · 7 年前

    在 组件一.ts 我正在发送数据 共享服务

      this.sharedService.sendData(this.getCheckedProduct);
    

    在 我订阅的数据就像,

          productList: any = [];
    
          getAllProducts: any = [];
    
          ngOnInit() {
            this.sharedService.getData().subscribe(data => {
              this.productList = data;
              this.getProduct();
            });
          }
    

    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;
      }
    

    我要把身份证给我 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) 函数i,获取 this.getAllProducts

    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 从共享服务数据。

    this.appService.getRest(AppConfig.settings.product.getProducts + '/' + element.product_obj_id).toPromise(); 获取所有产品 ..

    AppConfig.settings.product.getProducts 
    

    如何以异步方式实现。。到目前为止,我正在获取数据

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

    但在函数之外,我没有得到值,也没有 getAllProducts 不再使用html处理任何场景。。

    在 场景1

    this.getAllProducts = tempArray;
    

    因为我只给一个数组值 async

    简单地说,我需要从 this.getAllProducts 将从 service 使用get方法,我需要在url中传递一个id。。

    2 回复  |  直到 7 年前
        1
  •  1
  •   Pardeep Jain    7 年前

    只需在异步调用中分配数据,如下所示-

    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 .

        2
  •  0
  •   j4rey    7 年前

    AsyncPipe Observable . 在你的情况下,你是在应用它 getAllProducts 这是一个 Array ,我相信。所以你得到了那个错误。

    可能的解决方案:

    1. 去除 async 从你的for循环 获取所有产品
    2. 制造 你的

    注意:因为你是循环通过 productList 调用webapi来获取产品,您可能必须使用 mergeMap

    我相信解决方案2最适合你,因为你 产品列表 包含所有 产品 您需要点击webapi来获取 .

    学习MergeMap here

    示例代码(未测试&您需要添加用于错误处理的代码 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
    

    说明:

    因为你 是一个 阵列 你必须遍历它,然后对每个对象发出一个请求 product 反对 阵列

    from(this.productList) 产品列表 pipe 使用 合并地图 产品 this.appService.getRest(AppConfig.settings.product.getProducts + '/' + element.product_obj_id) 这个在里面 合并地图 . 那么我们 map response 我们从webapi获取数据,只使用 res['data'] . 最后我们 combineAll 返回一个 Observable<[]> 获取所有产品 ,因此 是一个 可见的 我们可以利用 异步管道

    编辑:

    在您的 constructor 而不是在 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()
    )
    
    推荐文章