Reputation: 4289
I am trying to migrate from angular HttpModule to angular HttpClientModule.
My current code working with HttpModule is as follows:
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');
}
In order to keep the same logic I have done the following:
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');
}
However, I am getting an error from the login function: "a function whose declare type either 'void' not any must return value". What is the right way to migrate my code to HttpClientModule?
Upvotes: 1
Views: 2267
Reputation: 222582
Just return the observable,
return this._http.post(this._candidateLoginUrl, body, { headers }).map((response: Response) => {
//consider returning the response and assign the token wherever you are consuming this method
})
Upvotes: 1