2016-01-17 41 views
2

我想让Angular2与我的Asp.Net WebApi 2服务器一起工作。我设法正确地处理了一些GET请求,但是这个POST请求的行为很奇怪。我收到我的服务器的OK(200)响应,但下面的代码将其视为一个错误:Angular2 - HTTP 200视为错误

public Register(){ 
    this.accountService.Register(this.Name, this.Password, this.RepeatPassword, this.Email, this.Skype, this.Website).subscribe(
     () => {  //this is what's supposed to be called, but isn't 
      this.accountService.Login(this.Name, this.Password).subscribe(
       res => { 
        console.log(res); 
        localStorage.setItem('token', res); 
        localStorage.setItem('user', this.Name); 
        this.router.navigate(['Home']); 
       }, 
       error2 => { 
        console.log(error2.Message); 
       } 
      ); 
     }, 
     error => { //the response gets here, instead of being handled above 
      console.log(error.Message); 
     } 
    ); 
} 

这里是帐户服务的注册方法:

public Register (userName:string, password:string, confirmPassword:string, email:string, skype:string, website:string) 
{ 
    return this.http.post(this.Uri + 'api/Account/Register', JSON.stringify(
     { 
      UserName: userName, 
      Password: password, 
      ConfirmPassword: confirmPassword, 
      Email: email, 
      Skype: skype, 
      Website: website 
     }), this.GetRequestOptions()).map((res: Response) => res.json()); 
} 

回答

3

终于找到了答案。 Ajax在预期json时,会在获取带有格式错误的json(包括空文件)的HTTP 200后触发错误回调。解决方法是用{}替换所有空的响应。

+1

你能在代码中显示你的修复吗?也经历类似的问题。 – markreyes