TypeError:不是函数typescript类

Aar*_*ron 12 javascript typescript angular

我在我的打字稿类中得到以下错误,无法理解为什么.我正在做的就是尝试调用传递令牌的辅助函数.

错误:发布错误:TypeError:this.storeToken不是函数(...)

类:

/**
 * Authentication Service:
 *
 * Contains the http request logic to authenticate the
 * user.
 */
import { Injectable } from '@angular/core';
import { Http, Response, Headers, RequestOptions } from '@angular/http';

import 'rxjs/Rx';
import { Observable } from 'rxjs/Observable';

import { AuthToken } from './auth-token.service';

import { User } from '../../shared/models/user.model';

@Injectable()
export class Authenticate {

  constructor(
    private http: Http,
    private authToken: AuthToken
  ) {}

  post(user: User): Observable<any> {
    let url = 'http://localhost:4000/';
    let body = JSON.stringify(user);
    let headers = new Headers({ 'content-type': 'application/json' });
    let options = new RequestOptions({ headers: headers });

    return this.http.post(url + 'login', body, options)
      .map(this.handleData)
      .catch(this.handleError);
  }

  private storeToken(token: string) {
    this.authToken.setToken(token);
  }

  private handleData(res: Response) {
    let body = res.json();
    this.storeToken(body.token);
    return body.fields || {};
  }

  private handleError(error: any) {
    console.error('post error: ', error);
    return Observable.throw(error.statusText);
  }
}
Run Code Online (Sandbox Code Playgroud)

我是打字稿的新手,所以我肯定我错过了一些非常简单的东西.任何帮助都会很棒.

谢谢.

Nit*_*mer 13

它应该是(使用Function.prototype.bind):

return this.http.post(url + 'login', body, options)
      .map(this.handleData.bind(this))
      .catch(this.handleError.bind(this));
Run Code Online (Sandbox Code Playgroud)

或(使用箭头功能):

return this.http.post(url + 'login', body, options)
      .map((res) => this.handleData(res))
      .catch((error) => this.handleError(error));
Run Code Online (Sandbox Code Playgroud)

发生的是您传递对方法的引用但它没有绑定到特定this的方法,因此当执行该方法时this,函数体中的不是类的实例,而是执行该方法的范围.

其中每一个都有助于保持正确的上下文this,但以不同的方式.


编辑

另一种选择是:

export class Authenticate {
    ...

    private handleData = (res: Response) => {
        ...
    }

    private handleError = (error: any) => {
        ...
    }
}
Run Code Online (Sandbox Code Playgroud)

通过这种方式,"方法"已经绑定,在这种情况下,它们不会成为原型的一部分,并且实际上将成为类型函数的属性.
例如:

class A {
    method1() { }
    method2 = () => {}
}
Run Code Online (Sandbox Code Playgroud)

编译为:

// es5
var A = (function () {
    function A() {
        this.method2 = function () { };
    }
    A.prototype.method1 = function () { };
    return A;
}());

// es6
class A {
    constructor() {
        this.method2 = () => { };
    }
    method1() { }
}
Run Code Online (Sandbox Code Playgroud)

因为这method2不能(轻易)重写,所以要小心这个实现.