2017-06-19 39 views
0

我已經添加了下面的代碼。基本上我想顯示錯誤消息到不同的場景(返回HTTP狀態代碼)。我試圖掌握所有關於觀測值等的概念,但到目前爲止我還沒有到達任何地方。希望有人能幫助我。如何在angular2中顯示不同的錯誤消息給不同的http錯誤?

export class HomePage { 

    private formData: FormGroup; 
    public errors: string = ""; 

    constructor(
    public navCtrl: NavController, 
    public authService: AuthServiceProvider, 
    public formBuilder: FormBuilder                                             
    ) { 

    this.formData = this.formBuilder.group({ 
     email: ['', Validators.compose([Validators.required,Validators.email])], 
     password: ['', Validators.required], 
    }); 


    doRegister(){ 
     this.authService.register(this.formData.value) 
     //Coming from angular 1 and I've honestly have no idea what I'm doing from here 
     .toPromise() 
     .then(data => this.navCtrl.push(ProfiePage,data)) 
     .catch((error: any) => { 
      /* 

      I want to show different msgs for different http erros 
      example 
      for 500 "username already exists" 
      for 400 " Invalid username" 
      for 401 "Someother error" 
      How do I do this? 

      */ 
      this.errors = "Username already exists"; 
     }); 

    } 


    } 

} 

@Injectable() 
export class AuthServiceProvider { 


    register(userData): Observable<UserModel[]>{ 
     // http error 500 will be return if there is an email exists error 
     return this.http.post(this.config.apiUrl+this.config.user.register,JSON.stringify(userData)) 
     .map((res: Response) => res.json()); 

    } 



} 





<ion-content padding id="page2"> 

/* I want to show the errors here */ 
{{error}} 

    <form [formGroup]="formData" (ngSubmit)="register()"> 
    <ion-list id="signup-list1"> 
     <ion-item id="signup-input5"> 
     <ion-label> 
      Email 
     </ion-label> 
     <ion-input type="email" placeholder="" formControlName="email"></ion-input> 
     </ion-item> 
     <ion-item id="signup-input6"> 
     <ion-label> 
      Password 
     </ion-label> 
     <ion-input type="text" placeholder="" formControlName="password"></ion-input> 
     </ion-item> 
    </ion-list> 
    <button [disabled]="!formData.valid" ion-button color="positive" block> 
     Sign up 
    </button> 
    </form> 


</ion-content> 

回答

0

您可以從服務拋出的錯誤,並在組件獲得

register(userData): Observable<UserModel[]>{ 
    return this.http.post(this.config.apiUrl+this.config.user.register, 
     JSON.stringify(userData)) 
     .map((res: Response) => res.json()) 
     .catch(
     (error: Response) => { 
      return Observable.throw(error.json() as JsonResponse) 
     });; 
} 

而在組件,您可以

test(): void { 
    this.testService.register().subscribe(
     (data: UserModel[]) => { 
      console.log(data); 
     }, (error: JsonResponse) => { 
      console.log(error); 
     } 
    ) 
} 
1

在catch塊中有錯誤對象將是一個狀態屬性,所以你可以訪問http錯誤代碼爲error.status。通過使用if條件來檢查這個error.status值,你可以處理你的場景。但看着你的代碼,似乎你正在從錯誤代碼創建驗證消息。我認爲從服務器返回驗證消息會更好(如果可以編輯API),而不是在代碼中操作它。因此,如果您想在將來更改驗證消息,則可以在不更改任何客戶端代碼的情況下執行此操作。