【发布时间】:2017-03-19 05:34:39
【问题描述】:
我正在开发一个 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);
}
}
- 我以这种方式在我的 LoginComponent 中使用它
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
- 我尝试在 stackoverflow 或 github 中搜索问题是否解决了这个问题,但我找不到对我有帮助的东西,所以如果有人可以帮助我处理 LoginComponent 中的错误作为服务的 handleError 方法的响应并获取我的组件中服务器的错误消息会很棒。 注意:成功部分工作正常问题是在我制作错误的情况下 return Observable.throw(res);
- 提前致谢
【问题讨论】:
-
您为什么要在登录组件中捕获错误,因为该错误将在服务中生成? (errorRes: any)=> { console.log('res in err is', error);我想可以记录错误
标签: javascript angularjs angular angular2-services