[英]angular2 component load problems
今天,我在Angular中遇到了一些奇怪的行为。
我有一个与API配合使用的应用程序,可从服务器获取数据。 以下是我猜对我的问题很重要的代码部分。
在使用其中一个ID进入ID的“详细信息”页面后,我得到了具有不同ID的JSON。 在此页面上,我使用goback()
函数再次进入列表。
第一次加载时,API数据被保存起来没有任何问题,返回后var tempPromotion
保持为空。 我的控制台错误为零。
可能是什么问题呢?
ngOnInit(): void {
// This is where i save the data from the API Call
this.promotionListService.getList().then((data) => {
this.tempPromotion = data;
this.tempPromotion = this.tempPromotion['response_payload'];
console.log(this.tempPromotion);
});
}
// This is the back Method which is called after a button click
goback() {
this.location.back();
}
//Get List Method define the API call
getList(): Promise<any> {
let Id = '1';
let serviceDec = "PromotionList";
return this.ApiClientService.getAPIObject(Id, serviceDec);
}
// get APIObject makes the call
getAPIObject(param: string, serviceDec: string) {
// Header mit Key aus LocalStorage
var header = new Headers();
header.append('Content-Type', 'application/json'); // immer zu erst Content-Type
header.append('x-api-key', this.key);
let options = new RequestOptions({ headers: header });
var urlTemp = this.url;
switch (serviceDec) {
case 'voucher':
urlTemp = urlTemp.concat('?promotionId='+param);
return this.http.get(urlTemp, options)
.toPromise()
.then((response: Response) => response.json())
.catch(this.handleError);
case 'PromotionList':
urlTemp = API_CLIENT[2];
return this.http.get(urlTemp, options)
.toPromise()
.then((response: Response) => response.json())
.catch(this.handleError);
case 'salesChannelList':
urlTemp = API_CLIENT[3].concat('?mode='+param);;
return this.http.get(urlTemp, options)
.toPromise()
.then((response: Response) => response.json())
.catch(this.handleError);
default:
console.error('An error occurred. Wrong service declaration.');
}
}
getList()
返回可观察值吗? 如果是这样,您需要像这样订阅它:
ngOnInit(): void {
// This is where i save the data from the API Call
this.promotionListService.getList().subscribe((data) => {
this.tempPromotion = data;
this.tempPromotion = this.tempPromotion['response_payload'];
console.log(this.tempPromotion);
});
}
重要的是要记住,可观察对象在subscribe
它们之前实际上不会向API发出请求。 因此,在您设置订阅之前,您将永远不会从可观察对象接收任何数据。 这可以解释为什么您也没有收到任何错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.