2016-01-17 64 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