I am trying to follow a simple pattern in the Angular 2 docs, but am having difficulty executing a function.
The example I am working from is here (app/toh/hero.service.ts (observable-based) file):
getHeroes (): Observable<Hero[]> {
return this.http.get(this.heroesUrl)
.map(this.extractData)
.catch(this.handleError);
}
addHero (name: string): Observable<Hero> {
let body = JSON.stringify({ name });
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
return this.http.post(this.heroesUrl, body, options)
.map(this.extractData)
.catch(this.handleError);
}
private extractData(res: Response) {
let body = res.json();
return body.data || { };
}
private handleError (error: any) {
// In a real world app, we might use a remote logging infrastructure
// We'd also dig deeper into the error to get a better message
let errMsg = (error.message) ? error.message :
error.status ? `${error.status} - ${error.statusText}` : 'Server error';
console.error(errMsg); // log to console instead
return Observable.throw(errMsg);
}
I need to store a token after the extractData
function, but do not think I'm calling it in right. I get it to work when I put it in the extraData
function, but I would like it to work on it's own:
private extractData(res: Response) {
let body = res.json();
if (body.response.user) {
return this.storeToken;
}
}
// want to call this function, but i'm doing something wrong
private storeToken(res: Response ) {
let resp = res;
console.log("resp", resp);
this.userId = resp.user.id;
this.token = resp.user.authentication_token;
localStorage.setItem('userId', this.userId);
localStorage.setItem('token', this.token);
return Rx.Observable.of('token', 'userId');
}
private handleError (error: any) {
// In a real world app, we might use a remote logging infrastructure
// We'd also dig deeper into the error to get a better message
let errMsg = (error.message) ? error.message :
error.status ? `${error.status} - ${error.statusText}` : 'Server error';
console.error(errMsg); // log to console instead
return Rx.Observable.throw(errMsg);
}
I am not sure if any data is being passed into the return this.storeToken
function, and I am not sure how to call it in the storeToken operator (res: Response)
.
I feel this is extremely basic, but I have been hung up on it so any help is greatly appreciated! Thank you!
Edit: This function works, but I would like to separate in two:
private extractData(res: Response) {
let body = res.json();
if (body.response.user) {
this.userId = body.response.user.id;
this.token = body.response.user.authentication_token;
console.log("id:", this.userId);
console.log("token:", this.token);
localStorage.setItem('userId', this.userId);
localStorage.setItem('token', this.token);
return Rx.Observable.of('token', 'userId');
}
}
Edit 2: Reading up on subscriptions and observables.