简体   繁体   English

TypeError:不是函数打字稿类

[英]TypeError: is not a function typescript class

I'm getting the following error in my typescript class and cannot understand why.我在打字稿类中收到以下错误,无法理解原因。 All I am doing is trying to call a helper function passing the token.我所做的就是尝试调用传递令牌的辅助函数。

Error:错误:

post error: TypeError: this.storeToken is not a function(…)发布错误:TypeError:this.storeToken 不是函数(...)

Class:班级:

/**
 * 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);
  }
}

I am new to typescript so I'm sure I am missing something ridiculously simple.我是打字稿的新手,所以我确定我错过了一些非常简单的东西。 Any assist would be great.任何帮助都会很棒。

Thanks.谢谢。

It should either be (using Function.prototype.bind ):它应该是(使用Function.prototype.bind ):

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

Or (using arrow functions ):或者(使用箭头函数):

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

What happens is that you are passing a reference to your method but it's not bound to a specific this , so when the method is executed the this in the function body isn't the instance of the class but the scope that executes the method.发生的情况是您传递了对方法的引用,但它没有绑定到特定的this ,因此当执行该方法时,函数体中的this不是类的实例,而是执行该方法的作用域。

Each of of those help keep the right context for this , but in a different way.这些中的每一个都有助于为this保持正确的上下文,但以不同的方式。


Edit编辑

Another option is:另一种选择是:

export class Authenticate {
    ...

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

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

In this way the "methods" are already bound, but in this case they won't be part of the prototype, and will in fact become just properties of type function.通过这种方式,“方法”已经被绑定,在这种情况下,它们不会成为原型的一部分,实际上将成为函数类型的属性。
For example:例如:

class A {
    method1() { }
    method2 = () => {}
}

Compiles to:编译为:

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

// es6
class A {
    constructor() {
        this.method2 = () => { };
    }
    method1() { }
}

Because of that method2 can't be (easily) overriden, so beware of this implementation.因为method2不能(容易)被覆盖,所以要注意这个实现。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM