问题描述
我的angular5应用程序中有一个组件:product-list.component.ts
.在此组件中,我有一个构造函数,该构造函数调用REST API.
I have an component in my angular5 application called: product-list.component.ts
. In this component I have a constructor, which calls a REST API.
product.service.ts
getAllProductsFromACategory(categoryName: string): any {
this.http.get('http://localhost:8080/VespaWebshopAPI
/api/Article/Category?categoryName=' + categoryName).
subscribe(data => {
var article: Article = {
id: data[0].id,
name: data[0].name,
articleNr: data[0].articleNr,
stock: data[0].stock,
price: data[0].price,
description: data[0].description
};
return article;
});
product-list.component.ts
public article: Article;
constructor(private route: ActivatedRoute,
private productService: productService) {
//Call rest api
this.article =
this.productService.getAllProductsFromACategory('Bremsen');
}
article.ts
export interface Article {
id : number;
name : string;
articleNr : string;
stock : number;
price : number;
description : string;
}
在我的html中,我想显示文章的某些属性.因此,如果我尝试在我的 product-list.component.html 文件中运行此代码,则会出现以下错误:
In my html, I want to display some properties of an article. So if I try to run this code in my product-list.component.html file, I get following error:
{{ article.id }}
错误
REST API有效;我测试了我想这只是问题,在显示html页面之前,应该先加载数据.在其他地方,我读到了ngFor
,我应该使用|.异步管道,但这对我不起作用.
The REST API works; I tested it. I guess there is just the problem that the data should get loaded first, before the html page gets displayed. Somewhere else I read that in an ngFor
, I should make use of the | async pipe, but that didn't work for me.
那我该如何解决呢?
推荐答案
@TNII,@Hoang Duc,尝试说您通常是服务公开Observables.订阅Observable时,它位于组件的ngOnInit中.
@TNII, @Hoang Duc, try say you is that generally a service expose Observables. It's in a ngOnInit in your component when you subscribe to the Observable.
//Simple return a get
getAllProductsFromACategory(categoryName: string): any {
return this.http.get('http://localhost:8080/VespaWebshopAPI
/api/Article/Category?categoryName=' + categoryName)
}
在组件中,通常当我们订阅时在ngOnInit中
In the component, generally in an ngOnInit when we subscribe to
ngOnInit()
{
productService.getAllProductsFromACategory('Bremsen').
subscribe(data => {
if (data[0])
this.article=data[0];
})
}
用html编写的{{article?.id}}是一种简短的说法:如果定义了this.article,请向我显示this.article.id.
the {{article?.id}} wrote in the html is a abreviate way to say: if this.article is defined, show me this.article.id.
检查是否在导航器中编写 http://localhost:8080/VespaWebshopAPI /api/Article/Category?categoryName ='Bremsen',为您提供一系列文章.检查数组的元素是否具有id,name等属性(或返回具有其他属性的元素)
check if when in a navigator write http://localhost:8080/VespaWebshopAPI/api/Article/Category?categoryName='Bremsen', give you an array of Articles. Check if the elements of the arrays has properties id,name,etc (or return element with another properties)
这篇关于角度5:如何等待服务完成,然后继续执行下一个任务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!