How to deal with http status codes other than 200 in Angular 2
现在我做http请求的方式(从此答案中借用)是这样的:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | POST(url, data) { var headers = new Headers(), authtoken = localStorage.getItem('authtoken'); headers.append("Content-Type", 'application/json'); if (authtoken) { headers.append("Authorization", 'Token ' + authtoken) } headers.append("Accept", 'application/json'); var requestoptions = new RequestOptions({ method: RequestMethod.Post, url: this.apiURL + url, headers: headers, body: JSON.stringify(data) }) return this.http.request(new Request(requestoptions)) .map((res: Response) => { if (res) { return { status: res.status, json: res.json() } } }); } |
除返回的状态代码不是200之外,angular2将会失败,事实是,此方法正常工作。例如,如果用户要发布内容并且服务器返回400,则angular 2将抛出异常:
uncaught exception: [object Object]
如何避免这种情况? 我想在我的应用中处理这些状态代码,以增强用户体验(显示错误等)
是的,您可以像这样使用catch运算符进行处理并根据需要显示警报,但是首先您必须以这种方式导入
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | import {Observable} from 'rxjs/Rx'; return this.http.request(new Request(this.requestoptions)) .map((res: Response) => { if (res) { if (res.status === 201) { return [{ status: res.status, json: res }] } else if (res.status === 200) { return [{ status: res.status, json: res }] } } }).catch((error: any) => { if (error.status === 500) { return Observable.throw(new Error(error.status)); } else if (error.status === 400) { return Observable.throw(new Error(error.status)); } else if (error.status === 409) { return Observable.throw(new Error(error.status)); } else if (error.status === 406) { return Observable.throw(new Error(error.status)); } }); } |
您还可以处理
像这样 -
1 2 3 | ... .subscribe(res=>{....} err => {//handel here}); |
更新资料
根据任何状态的要求而无需检查特定状态,您可以尝试以下操作:-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | return this.http.request(new Request(this.requestoptions)) .map((res: Response) => { if (res) { if (res.status === 201) { return [{ status: res.status, json: res }] } else if (res.status === 200) { return [{ status: res.status, json: res }] } } }).catch((error: any) => { if (error.status < 400 || error.status ===500) { return Observable.throw(new Error(error.status)); } }) .subscribe(res => {...}, err => {console.log(err)} ); |
包括必需的导入,您可以在handleError方法中做出决定
错误状态将给出错误代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | import { HttpClient, HttpErrorResponse } from '@angular/common/http'; import {Observable, throwError} from"rxjs/index"; import { catchError, retry } from 'rxjs/operators'; import {ApiResponse} from"../model/api.response"; import { TaxType } from '../model/taxtype.model'; private handleError(error: HttpErrorResponse) { if (error.error instanceof ErrorEvent) { // A client-side or network error occurred. Handle it accordingly. console.error('An error occurred:', error.error.message); } else { // The backend returned an unsuccessful response code. // The response body may contain clues as to what went wrong, console.error( `Backend returned code ${error.status}, ` + `body was: ${error.error}`); } // return an observable with a user-facing error message return throwError( 'Something bad happened; please try again later.'); }; getTaxTypes() : Observable<ApiResponse> { return this.http.get<ApiResponse>(this.baseUrl).pipe( catchError(this.handleError) ); } |