http - Angular 2私有(private)变量消失

标签 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”指的是另一个对象,还是 ActionSerivce 的局部变量在发生 http 异常时为空。经过身份验证的局部变量已正确注入(inject)(我在构造函数中做了一个 console.log,它就在那里)。

最佳答案

问题是您没有在回调函数中绑定(bind) 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 => {    
    //...
} 

关于http - Angular 2私有(private)变量消失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38951327/

相关文章:

http - 使下载 .rtf 文件成为可能

javascript - AngularJS:使用 $http.get 检索数据并使其可用

java.net.UnknownHostException : http://localhost:8082/consume/create

javascript - 如何将查询参数添加到防护中的路由并将其传递给Angular 4中的组件?

angular - 如何在 angular-cli@webpack 完成捆绑后运行 gulp 任务?

php - 在 php 中通过 post 接收 xml 文件

angular - 用 jest 测试 Angular 组件给出了resolveComponentResources

dictionary - 在 Tcl 中检查参数是否为字典

javascript - 通过 fetch promises 处理响应错误/http 状态

c# - Try/Catch——我怎么知道在奇怪/复杂的情况下要捕捉什么?