我试图从我写的承诺中获得一个名字,我可以用邮递员访问API,在“网络”标签中可以看到请求,但在控制台中却遇到了解析错误。
我的组件看起来像
generateAppointments(companyID): any {
this.appointments = null;
this.appointmentService.getAppointmentsByCompanyID(companyID).then(r => {
console.log(r);
this.appointments = r;
this.appointments.forEach((item, index) => {
let customerName = this.getCustomerNameByID(item.customerID);
console.log(customerName);
let newAppointment = {
id: item.appointmentID,
description: item.appointmentNotes,
subject: customerName,
//calendar: this.getCustomerNameByID(item.customerID),
observCat: item.customerID,
observSub: item.observationCategoryID,
start: new Date(item.appointmentDate),
end: new Date(item.appointmentEndDate),
}
this.scheduler.addAppointment(newAppointment);
});
});
//console.log(this.source);
};
调用
getCustomerNameByID(customerID) {
this.appointmentService.getCustomerNameByCustomerID(customerID)
.then(data => { this.customerName = data; return data; }).catch(err =>
console.log(err));
}
服务承诺如下:
getCustomerNameByCustomerID(customerID): Promise<string> {
return this.httpClient.get<string>(this.baseUrl +
'api/Appointments/GetCustomerNameByCustomerID?CustomerID=' + customerID)
.toPromise()
.then((res) => { console.log(res); return res; });
}
}
我的Chrome控制台错误是:
"SyntaxError: Unexpected token S in JSON at position 0
at JSON.parse (<anonymous>)
at XMLHttpRequest.onLoad (http://localhost:5000/vendor.js:7509:51)
at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (http://localhost:5000/polyfills.js:2768:31)
at Object.onInvokeTask (http://localhost:5000/vendor.js:48600:33)
at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (http://localhost:5000/polyfills.js:2767:60)
at Zone.push../node_modules/zone.js/dist/zone.js.Zone.runTask (http://localhost:5000/polyfills.js:2540:47)
at ZoneTask.push../node_modules/zone.js/dist/zone.js.ZoneTask.invokeTask [as invoke] (http://localhost:5000/polyfills.js:2843:34)
at invokeTask (http://localhost:5000/polyfills.js:4089:14)
at XMLHttpRequest.globalZoneAwareCallback (http://localhost:5000/polyfills.js:4126:21)"
它返回并尝试解析的文本为"Smith,Benjamin 0014662"
,我不知道为什么它试图解析JSON,我只想找回那个值。
我正在尝试在newAppointment变量中设置该值,但是它要求subject:
是一个字符串,但抱怨它是无效的,我认为这是无关的但不确定。
我是新手,所以我对这一切都不是很熟悉。端点返回我想要的东西,但是我不确定为什么它认为需要从JSON解析结果。
编辑,我有一个console.log(customerName),它返回未指定的内容。就像我说的那样,API返回:"Smith,Benjamin 0014662"
,但是我的TS没有获得该值,而是抱怨解析错误。
答案 0 :(得分:0)
首先检查返回的json,当json语法错误时,它会发生,如果不是这种情况,则将aponments声明为数组
let appointments =[];
答案 1 :(得分:0)
由于该API返回了文本正文,因此您可以执行以下操作。
getCustomerNameByCustomerID(customerID): Promise<string> {
return this.httpClient.get(this.baseUrl +
'api/Appointments/GetCustomerNameByCustomerID?CustomerID=' + customerID, { responseType: 'text' })
.toPromise()
.then((res) => { console.log(res); return res; });
}
仅供参考:默认情况下,除非另有说明,否则HttpClient尝试将响应解析为JSON对象。将responseType添加为text
将使HttpClient期望响应为字符串而不是解析它。