服务
HTTP post服务
addUser(body: Object): Observable<any> {
let bodyString = JSON.stringify(body);
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
return this.http.post(this.baseUrl + 'api/v3/user/Adduser', body, options)
.map((res: Response) => res.json())
.catch((error: any) => Observable.throw(error.json().error || 'Server error'));
}
组件
当我调用此方法时,数据将被插入数据库,但我无法获得响应。它进入了错误块。请查看下面的图片以获取错误信息。
addUser(items: any) {
this.signupService.addUser(items)
.subscribe(response => {
this.eventsEmitter.broadcast('Success', 'Changes Saved Succesfully');
this.router.navigate(['/login']);
},
error => {
debugger;
this.eventsEmitter.broadcast('Error', 'Error Occured');
});
}
错误信息
不确定如何解决此问题。你能告诉我改变它的工作吗?
Web API控制器
这是Web API控制器
[HttpPost]
[Route("AddUser")]
public async Task<IHttpActionResult> AddUser([FromBody]UsersModel model)
{
try
{
await _userService.AddUser(model);
HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.Created);
return ResponseMessage(response);
}
catch (Exception ex)
{
return InternalServerError(ex);
}
}
答案 0 :(得分:2)
尝试进行以下更改:
addUser(items: any) {
this.signupService.addUser(items)
.subscribe(response => {
this.eventsEmitter.broadcast('Success', 'Changes Saved Succesfully');
this.router.navigate(['/login']);
});
}
Web API Controller:
[HttpPost]
[Route("AddUser")]
public async Task<IHttpActionResult> AddUser([FromBody]UsersModel model)
{
try
{
await _userService.AddUser(model);
HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
return ResponseMessage(response);
}
catch (Exception ex)
{
return InternalServerError(ex);
}
}
Http服务:
addUser(body: Object): Observable<any> {
let bodyString = JSON.stringify(body);
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
return this.http.post(this.baseUrl + 'api/v3/user/Adduser', body, options)
.map((response : Response) => {
if (response.status < 200 || response.status >= 300) {
throw new Error('This request has failed ' + response.status);
}
else {
return response.json();
}
});
}
答案 1 :(得分:0)
确保导入必要的依赖项:
import { Observable } from "rxjs/Observable";
import 'rxjs/add/observable/throw';