2017-08-27 122 views
0

我想檢測到服務器的連接錯誤,以便我可以向用戶顯示適當的消息。在Angular 2中檢測服務器連接錯誤(404狀態)

當後端服務器(Web API)關閉時,我試圖通過使用http.get來訪問此服務器上的方法我期望得到404狀態或某種連接的響應錯誤。而是我越來越

「與狀態響應:URL 0:空」

這是不明確的。 那麼我該如何檢測連接錯誤呢?

這是相關代碼:

登錄組件:

this.loginService.tryLogin(userName, password).subscribe(_loginStatus => { 
    //Some operations 
}, 
_err => this.errMsg = _err; // this.errMsg will be displayed to the user 
); 

登錄服務

tryLogin(user: string, pwd: string): Observable<LoginStatus> { 
return this.http.get(this.serverUri + `Login/?username=${user}&password=${pwd}`) 
    .map(response => response.json()) 
    .catch(err => this.handleError(err)); 
} 

private handleError(error: any) { 
    const err = (error.json() ? error.json() : error); 
    console.log(err); 
    return Observable.throw(err); 
} 
+0

你檢查嗎? $ {pwd} –

+0

@PadmanabanGokula oops之後結束單引號缺失,現在修復它 – cookya

回答

1

可以使Http Interceptors這裏使用。在Angular中使用新的攔截器很容易。

import { Observable } from 'rxjs'; 
import {Injectable} from '@angular/core'; 
import {HttpEvent, HttpInterceptor, HttpHandler, HttpRequest} from '@angular/common/http'; 
import { HttpErrorResponse } from "@angular/common/http"; 

@Injectable() 
export class AngularInterceptor implements HttpInterceptor { 
    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { 
    return next.handle(req).do(event => {}, err => { 
     if(err instanceof HttpErrorResponse){ // here you can even check for err.status == 404 | 401 etc 
      console.log("Error Caught By Interceptor"); 
      //Observable.throw(err); // send data to service which will inform the component of the error and in turn the user 
     } 
    }); 
    } 
} 

註冊此在的AppModule像

providers: [ 
     [ { provide: HTTP_INTERCEPTORS, useClass: 
       AngularInterceptor, multi: true } ] 
    ], 

有關HTTP客戶端和攔截的詳細信息檢查此link