Angular 2私有变量消失

时间:2016-08-15 07:57:48

标签: http angular catch-block

我有以下代码,这是一个简单的服务,可以返回服务器来获取一些数据:

import { Injectable } from '@angular/core';
import { Action } from '../shared';
import { Http, Response, Headers, RequestOptions } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import { Authenticated } from '../authenticated';
import 'rxjs/Rx';

@Injectable()
export class ActionsService {
    private url = 'http://localhost/api/actions';
    constructor(private http: Http, private authenticated : Authenticated) {}

getActions(search:string): Observable<Action[]> {
    let options = this.getOptions(false);

    let queryString = `?page=1&size=10&search=${search}`; 
    return this.http.get(`${this.url + queryString}`, options)
                .map(this.extractData)
                .catch(this.handleError);
}

private extractData(response: Response) {
    let body = response.json();
    return body || { };
}

private handleError (error: any) {      
    let errMsg = (error.message) ? error.message : error.status ? `${error.status} - ${error.statusText}` : 'Server error';    
    console.error(errMsg); // log to console instead

    if (error.status == 403) {            
      this.authenticated.logout();
    }

    return Observable.throw(errMsg);
}     

private getOptions(addContentType: boolean) : RequestOptions {
    let headers = new Headers();
    if (addContentType) {
      headers.append('Content-Type', 'application/json');  
    }

    let authToken = JSON.parse(localStorage.getItem('auth_token'));        
    headers.append('Authorization', `Bearer ${authToken.access_token}`);

    return new RequestOptions({ headers: headers });
  }
}

除handleError外,一切都按预期工作。一旦getActions从服务器收到错误,它就会进入this.handleError方法,该方法再次正常工作,直到应该调用this.authenticated.logout()的部分。 this.autenticated是未定义的,我不确定是否因为“this”指的是另一个对象,或者当发生http异常时ActionSerivce的局部变量为null。正确注入经过身份验证的局部变量(我在构造函数中执行了console.log,它就在那里)。

1 个答案:

答案 0 :(得分:2)

问题是您没有绑定回调函数中的this上下文。您应该声明http这样的电话,例如:

return this.http.get(`${this.url + queryString}`, options)
                .map(this.extractData.bind(this))    //bind
                .catch(this.handleError.bind(this)); //bind

另一种选择可能是传递一个匿名函数并从那里调用回调:

return this.http.get(`${this.url + queryString}`, options)
                .map((result) => { return this.extractData(result)})
                .catch((result) => { return this.handleError(result}));

另一种选择是宣布您的回调功能略有不同,您可以按照以前的方式保留http来电:

private extractData: Function = (response: Response): any => {
    let body = response.json();
    return body || { };
}

private handleError: Function = (error: any): any => {    
    //...
}