角度 2:由于接收服务器数据缓慢而导致接收错误



在我的服务类的构造函数中,我对服务器进行了 http 调用,以检索存储在 productCategory 数组中的产品类别数据。然后在组件的 ngInit(( 函数中,我调用服务以检索 productCategory 数组,但出现错误,指出 productCategory 未定义。

似乎正在发生的事情是服务的构造函数调用服务器,然后在检索产品类别数据之前返回。当组件为此数据调用服务的 getCategory(x, y( 方法时,服务构造函数对服务器的先前调用仍未完成,因此它声明 productCategory 数组未定义。然后,调用完成,产品类别数组将记录到控制台。

我该如何解决这个问题?

@Injectable()
export class ProductCategoryService {
private productCategories: ProductCategory[];
private categoriesUrl = "/api/product/categories";
constructor(private http: Http) { 
console.log('ProductCategory.constructor() called');
this.getProductCategoriesDb();
}
private getProductCategoriesDb() {
console.log('ProductCategory.getCategories() called');
this.http.get(this.categoriesUrl)
.toPromise()
.then((response: Response) => {
this.productCategories = response.json();
console.log('this.productCategories = ' + 
JSON.stringify(this.productCategories));
})
.catch(this.handleError);
}
public getProductCategory(name, type) {
return this.productCategories
.filter(category => (category.name == name && category.type == type))[0];
}
}

元件:

export class ProductCategoryComponent implements OnInit {
category: string;
type: string;
productCategory: ProductCategory = new ProductCategory();
constructor(private route: ActivatedRoute, private productCategoryService: 
ProductCategoryService) { }
ngOnInit() {
this.route.params.subscribe(params => {
this.category = params["category"];
this.type = params["type"];
console.log("category = " + this.category)
console.log("type = " + this.type)

this.productCategory = 
this.productCategoryService.getProductCategory(this.category, this.type);
console.log("productCategory = " + this.productCategory);
})  
}
}

记录语句的顺序:

ProductCategory.constructor(( 调用---- product-category.service.ts:27

ProductCategory.getCategories(( 称为 ---- product-category.component.ts:23

错误:未定义产品类别数组:

ProductCategoryComponent_Host.html:1 错误类型错误:无法读取未定义的属性"过滤器" at ProductCategoryService.webpackJsonp.../../../../../src/app/product-category/product-category.service.ts.ProductCategoryService.getProductCategory (product-category.service.ts:39( at SafeSubscriber._next (product-category.component.ts:27( at SafeSubscriber.webpackJsonp.../../../../rxjs/Subscriber.js.SafeSubscriber.__tryOrSetError (

最后产品类别数组打印---产品类别.服务.ts:33

this.productCategory = [{"_id":"599c5d93f36d286317108ff","name":"家具","type":"客厅","图像":[{"标签":"客厅","名称":"客厅1.jpg"},{"标签":"沙发","名称":"客厅2.jpg"},{"标签":"卧铺","名称":"客厅3.jpg"},{"标签":"LoveSeats","name":"LivingRoom4.jpg"},{"label":"Chairs","name":"LivingRoom5.jpg"},{"label":"HabitRoom5"},{"label":"Ottomans","name":"LivingRoom6.jpg"},{"label":">

Chaisers","name":"LivingRoom7.jpg"},{"label":"躺椅","name":"客厅8.jpg"},{"标签":"分段","名称":"客厅9.jpg"},{"标签":"临时桌子","名称":"客厅10.jpg"}],"物品":["沙发","卧铺","双人座椅","椅子","脚凳","躺椅","躺椅","组合式","临时桌子"]}]

简短的回答是不要修复它,重写它。 抛出错误背后的推理是正确的,但在处理来自服务器的数据时,也许您应该考虑不同的方法。

这是第一步,可以进一步迭代改进。

@Injectable()
export class ProductCategoryService {
productCategoriesSbj: ReplaySubject<ProductCategory[]> = new ReplaySubject();
private categoriesUrl = "/api/product/categories";
constructor(private http: Http) { 
}
getProductCategoriesDb(): Observable<ProductCategory[]> {
return this.http.get(this.categoriesUrl)
.subscribe(response => this.productCategoriesSbj.next(response.json()))
.catch(this.handleError);
}
getProductCategory(categories: ProductCategory[], name: string, type: string) {
return categories.filter(category =>
(category.name == name && category.type == type)
)[0];
}
}

然后在您的组件中:

export class ProductCategoryComponent implements OnInit, OnDestroy {
category: string;
type: string;
productCategory: ProductCategory = new ProductCategory();
productCategorySub: Subscription = new Subscription();
constructor(private route: ActivatedRoute,
private productCategoryService: ProductCategoryService){
}
ngOnInit() {
this.route.params.subscribe(params => {
this.category = params["category"] || '';
this.type = params["type"] || '';
this.productCategoryService.getProductCategoriesDb();
productCategorySub = this.productCategoryService
.productCategoriesSbj
.subscribe(categories => {
// now categories contain parsed response from the server
this.productCategory = this.productCategoryService
.getProductCategory(categories, this.category, this.type);
});
})  
}
}
ngOnDestroy() {
// unsubscribe from observable to avoid memory leaks
this.productCategorySub.unsubscribe();
}

解释不多,但我希望它有所帮助。

最新更新