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 这是很长时间以来的问题,无法解决,任何帮助将不胜感激。
解决方案
在任何角度绑定或 ngIf 中调用函数几乎总是会导致无限循环,因为任何触发更改检测的东西都会导致再次调用该函数。这通常会导致您的应用程序变慢和大量延迟,应始终避免。
对于您的场景,当您的产品数组被填充时,我会 1. 遍历产品,查找外键并将属性添加到产品(或将其克隆到“显示”数组) 2. 遍历产品并生成查找与外键链接的数组。您可以显示此数组以获取您的产品类别。
出于性能原因,我会尽量避免在 ngfor 中进行任何订阅 find 调用。
祝你好运
推荐阅读
- android - 未找到 id 片段的视图
- azure - 如果一段时间没有使用 Azure 网站会很慢
- gps - 来自 SIM7600E 的 GPS 数据
- java - 对固定数据使用 java 序列化对象
- html - 将 CSS 模块与 Bootstrap 相结合
- javascript - Flatpickr:添加 enableTime 选项时无法清除输入
- laravel - 如何在不更改 url 的情况下将变量从刀片发送到控制器
- regex - 使用正则表达式修改原始输入以使其看起来像特定格式的巴士时间表?
- algorithm - 给定一棵树,计算这棵树中的最长路径,其路径中的节点具有相同的设置位
- java - 尝试在空对象引用上调用虚拟方法。数组列表