我正在尝试从有角度的 HttpModule 迁移到有角度的 HttpClientModule。
我当前使用 HttpModule 的代码如下:
constructor(private _http: Http) { }
token: IToken;
errorMesage: string;
private _candidateLoginUrl = 'http://myapi/v1/auth/login';
login(userName: string, password: string): Observable<IToken> {
let body = JSON.stringify({ username: userName, password: password });
let headers = new Headers();
headers.append("Content-Type", 'application/json');
let options = new RequestOptions({ headers: headers });
return this._http.post(this._candidateLoginUrl, body, options)
.map((response: Response) => {
this.token = <any>response.json().data;
if (this.token && this.token.token) {
localStorage.setItem('currentUser', JSON.stringify(this.token));
}
return this.token;
})
.catch(this.handleError);
}
private handleError(error: Response) {
return Observable.throw('You are not authorized to get this resource');
}
为了保持相同的逻辑,我做了以下事情:
constructor(private _http: HttpClient) { }
token: IToken;
errorMesage: string;
private _candidateLoginUrl = 'http://myapi/v1/auth/login';
login(userName: string, password: string): Observable<IToken> {
let body = JSON.stringify({ username: userName, password: password });
const headers = new HttpHeaders().set("Content-Type", 'application/json');
this._http.post(this._candidateLoginUrl, body, { headers })
.map((response: Response) => {
this.token = <any>response;
if (this.token && this.token.token) {
localStorage.setItem('currentUser', JSON.stringify(this.token));
}
return this.token;
})
.catch(this.handleError);
}
private handleError(error: Response) {
return Observable.throw('You are not authorized to get this resource');
}
但是,我从登录函数中收到一个错误:“声明类型为 'void' 而不是任何必须返回值的函数”。将我的代码迁移到 HttpClientModule 的正确方法是什么?