我正在开发一个Angular 2 Apllication,我的登录功能就是这项服务。
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
答案 0 :(得分:0)
当引发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);
})
答案 1 :(得分:0)
您需要导入Observable.throw()
。
添加此导入语句:
import 'rxjs/add/observable/throw';