使用 Observables 时处理服务器错误

Handle server error while using Observables

我正在开发一个 Angular 2 应用程序,我的登录功能中包含此服务。

import { Http, Response } from '@angular/http';
import {Injectable} from '@angular/core';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/catch';
import { Observable } from 'rxjs/Observable';
import { contentHeaders, apiUrl} from '../shared/headers';
@Injectable()
export class LoginService extends BaseService{
constructor(private http: Http){
super();
}
/**
* send the user login data (email, password) and the token back to be stored on the client side.
* @param user
* @returns {any|Promise}
*/
login(user: any): Observable<any>{
let body = JSON.stringify(user);
return this.http.post(apiUrl + '/login', body, { headers: contentHeaders })
.map(this.extractData)
.catch(this.handleError);
}
/**
* extract response data and return it to the component
* @param res
* @returns {*}
*/
public extractData(res: Response) {
let body = res.json();
console.log(body);
return body;
}
/**
* handle service error
* @param error
* @returns {ErrorObservable}
*/
public handleError(res: Response) {
return Observable.throw(res);
}
}

this.loginService.login(userObj)
.subscribe(
(response: any) => {
// success call that is Ok
},
(errorRes: any)=> {
console.log('res in err is', error);
}

-我组件中console.log的结果是

TypeError: Observable_1.Observable.throw is not a function

当引发 throw 时,您应该使用 catch 运算符处理,如下所示

getTasks(): Observable<any[]> {
        return this._http.get(this._url)
            .map((response: Response) => <any[]>response.json())
            .do(data => console.log("data we got is " + JSON.stringify(data)))
            .catch(this.handleError);

    }
    private handleError(error: Response) {
            console.log(error);
                    }

此外,您在错误处理程序方法中再次抛出错误,不应该如此

this.loginService.login(userObj)
.subscribe(
(response: any) => {
// success call that is Ok
},
(error)=> {
////////////////////////error message is available in this object
console.log('res in err is', error);

})

您需要导入 Observable.throw().

添加此导入语句:

import 'rxjs/add/observable/throw';