Angular - 总是在请求中得到“[Object object]”错误(即使请求有效)

时间:2018-04-27 13:16:25

标签: angular typescript angular-httpclient

我在角度应用上面临一个奇怪的问题:

我创建了一个注册表单组件,它使用服务方法向服务器发送带有注册数据的http post请求。
如果注册正常,它会返回一个字符串,否则会返回错误的请求。

问题:

现在,问题是即使注册正常(我的db表已填满并且用户已创建),我的注册http方法始终会运行http请求方法的“错误”部分。

错误只是说“[Object object]”,我的服务返回“Account created”字符串作为成功响应

为什么总是会抛出错误?我该如何解决这个问题?

我与您分享下面的代码:

  

注册组件.ts - 注册方法

registerUser({ value, valid }: { value: UserRegistration, valid: boolean }) {
    this.submitted = true;
    this.isRequesting = true;
    this.errors='';
    if(valid)
    {
        this.userService.register(value.email,value.password,value.firstName,value.lastName,value.location)
                  .finally(() => this.isRequesting = false)
                  .subscribe(
            result => {
                console.log(result);
                if (result) {                      
                        this.router.navigate(['/login']);                         
                    }},
            errors => { console.error(errors); this.errors = errors });
    }      
 } 
  

注册服务方法 - http请求

register(email: string, password: string, firstName: string, lastName: string, location: string): Observable<any> {
        let body = JSON.stringify({ email, password, firstName, lastName, location });
        let headers = new HttpHeaders().set('Content-Type', 'application/json')

        return this.http.post(this.baseUrl + "/Accounts/NewUser", body, { headers })
            .map(res => { return true })
            .catch(error => Observable.throw(error));  //ALWAYS PASSES THROUGH HERE
    }
  

MY API

[HttpPost("NewUser")]
        public async Task<IActionResult> NewUser([FromBody]RegistrationViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            var userIdentity = _mapper.Map<AppUser>(model);

            var result = await _userManager.CreateAsync(userIdentity, model.Password);

            if (!result.Succeeded) return new BadRequestObjectResult(Errors.AddErrorsToModelState(result, ModelState));

            await _appDbContext.Customers.AddAsync(new Customer { IdentityId = userIdentity.Id, Location = model.Location });
            await _appDbContext.SaveChangesAsync();

            return new OkObjectResult("Account created");
        }

0 个答案:

没有答案