如何使用Angular中的外键获取数据

时间:2019-05-28 05:19:59

标签: angular-meteor

我试图用Meteor实现Angular并成功实现了。我试图以这种方式从我的收藏中获取数据。 这是我用来在表格中呈现数据的代码

<ng-container *ngFor="let product of products;let i=index">
          <tr >
              <td>{{ i+1}}</td>
              <td>{{product.product_name}}</td>
              <td >{{product.product_category_id 
                  | fetch_product_category}}</td> // Approach 1
              <td >{{getProductCateogry(product.product_category_id)}} 
              </td> // Approach 2
              <td>{{product.product_brand}}</td>
              <td>{{product.created_at | date}}</td>
            <tr/>
 </ng-container>

在“产品名称和品牌”中获取数据,但不在“产品类别ID”中获取数据。 产品类别是另一个具有类别名称的集合。 为了获得产品类别中的数据,我使用了以下方法 方法1-Angular Pipe(我在Angular中使用了它) 这是我创建的管道类

 @Pipe({
      name: 'fetch_product_category'
     })
  export class FetchProductCategory implements PipeTransform {
     private productCategory: any;

    transform(catId: string): string {
    var productCatListingSubs = 

MeteorObservable.subscribe('fetch_product_category_based_on_categoryid',
  catId).subscribe( => {
        var productCategory = 
        ProductCategory.find({"product_category_id":catId}).fetch();
         console.log("Products Category  :",this.productCategory); // Getting Data Here
      });
        console.log("Products Category  :",this.productCategory); // Data not returned here
        return this.productCategory;  
    }
  }

方法2:根据订阅获取数据

getProductSubcategory(catId){
   var name;
   console.log("Products Category"catId);
   this.productCatListingSubs = MeteorObservable.subscribe('fetch_product_category_based_on_categoryid',catId).subscribe( => {
      var productCategory = ProductCategory.find({"product_category_id":catId}).fetch();
       console.log("Products Category",productCategory);
       name = productCategory[0].product_category_name;
       console.log("name  :",name); 
     });
     return name;
 }

在第二种方法中,数据存在,但控制台中为此存在无限循环。 我正在使用METEOR@1.8.0.1和ANGULAR@7.1.1 这是很长一段时间的问题,无法解决,任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

在任何角度绑定或ng中调用函数几乎总是会导致无限循环,因为任何触发更改检测的事物都会导致再次调用该函数。这通常会导致应用速度变慢和大量延迟,因此应始终避免。

对于您的情况,当您填充产品数组时,我要么 1.循环浏览产品,查找外键并为产品添加属性(或将其克隆到“显示”数组中) 2.循环浏览产品,并生成与外键链接的查找数组。您可以显示此数组以获取您的产品类别。

出于性能原因,我会尽量避免在ng内部进行任何订阅查找呼叫。

祝你好运