我正在制作http post
,然后尝试将值分配给subscribe中的局部变量。
然而,永远不会调用局部变量代码行。为什么?我的代码有什么问题?
这是我的组件
submitted = false;
onSubmit() {
this.leaveService.addLeave(this.model)
.subscribe(res => {
this.submitted = true; **// This line of code never execute. Why?**
});
}
这是我的服务
addLeave(body: leave): Observable<leave[]> {
let bodyString = JSON.stringify(body); // Stringify payload
let headers = new Headers({ 'Content-Type': 'application/json' }); // ... Set content type to JSON
let options = new RequestOptions({ headers: headers }); // Create a request option
return this.http.post(this._apiUrl, body, options)
.map(res => res.json())
.catch((error: any) => Observable.throw('Error'));
}
我的MVC控制器方法(只需添加简单的一个以确保往返很好)
[HttpPost("[action]")]
public IActionResult CreateLeaveRequest([FromBody] LeaveModel leave)
{
return StatusCode(200);
}
}
我在控制台中看不到任何错误。 如果您需要更多信息来了解问题,请告诉我。
注意:
onSubmit()绝对称为。序列是调用OnSubmit(),它从服务调用addLeave,将请求发送到控制器方法(调试点命中)。
答案 0 :(得分:1)
你的.map函数需要返回一些东西......
return this.http.post(this._apiUrl, body, options)
.map(res => {
console.log(res) // Log here to see what you get in response body
return res.json() || []; // if response has no json then return []
)
.catch((error: any) => Observable.throw('Error'));
}
答案 1 :(得分:0)
当Observable发出一个项目时,会执行传递给订阅的第一个函数。如果帖子没有返回值并且您没有手动映射响应,则不会发出任何项目并且不执行此功能:
.subscribe(res => {
this.submitted = true; **// This line of code never execute. Why?**
});
您需要从Observable中发出一个项目,或者您可以尝试使用subscribe的第三个参数并在完成时执行代码,而不是在发出时执行。
.subscribe(
() => {}, **// On emit
err => {}, **// On error
() => {
this.submitted = true; **// On complete **
});