【发布时间】:2018-07-29 20:01:22
【问题描述】:
我正在尝试使用 HttpClient 从 Angular 4 对 web api 进行后期调用。
这是我的后调用服务:
public add<T>(type:string, item: T): Observable<any> {
console.log("api data : " + this.url + type);
return this.http
.post(this.url + type, JSON.stringify(item)).map((res: Response) => { console.log("rese: "+res); res});
}
这是订阅上述服务的代码:
addArticleType(articleType: ArticleType): void {
console.log("Service data : " + articleType);
this.service.add("ArticleType", articleType).subscribe((val: any) => this.response = val),
(error: any) => { console.log("Error is: " + error) },
() => { console.log("resp: " + this.response) };
}
这是 API
public HttpResponseMessage Add(A item)
{
int a = this.service.Add(item);
log.Debug("value: " + a);
if (a > 0)
{
var response = Request.CreateResponse(HttpStatusCode.OK);
response.Content = new StringContent("Data saved successfully.", Encoding.UTF8, "application/json");
return response;
}
return Request.CreateErrorResponse(HttpStatusCode.ExpectationFailed, "Failed to save data");
}
在 Post 调用时,API 接收调用并执行将数据存储在数据库中的任务。但是 Angular 不会接收 API 作为 HttpResponseMessage 发送的任何响应。
正如您在服务中看到的,我正在尝试在控制台中打印响应。这总是打印空值。作为回应,我希望 API 发送的消息“数据已成功保存。”,但我得到的是空值。
我可能遗漏了一些非常基本的东西。我查看了很多文章和博客,但没有找到任何可以解决问题的方法。
更新:
根据提供的指南,我更新了我的代码,如下所示。
通话后
public add<T>(type:string, item: T): Observable<T> {
console.log("api data : " + this.url + type);
return this.http
.post<T>(this.url + type, item);
}
订阅
addArticleType(articleType: ArticleType): void {
console.log("Service data : " + articleType);
this.service.add<ArticleType>("ArticleType", articleType)
.subscribe(
(val: any) => {
this.response = val;
console.log("res sub: " + this.response);
},
(error: any) => { console.log("Error is: " + error) },
() => { console.log("resp: " + this.response) });
}
它仍然在控制台中将响应打印为 null。
【问题讨论】:
-
1st) 你为什么要把身体串起来? 2nd)你永远不会映射响应
-
为什么你认为
HttpClient.post方法的响应类型是Response?请阅读 angular.io 中的 http 指南 -
而且add方法里面的map应该有return。
-
@Jota.Toledo 我们不知道他使用的是 httpclient 而不是 http。并且地图不需要返回,但可能需要变为
.map(res => res.json()) -
您能在开发控制台的“网络”选项卡中看到到达的响应吗?
标签: angular asp.net-web-api rxjs