Angular 2 http Post在客户端失败,但数据已插入数据库中

时间:2017-01-16 04:15:23

标签: http angular

服务

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');
        });
}

错误信息

error

不确定如何解决此问题。你能告诉我改变它的工作吗?

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);
    }
}

2 个答案:

答案 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';