typescript TypeError:不是函数打字稿类
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40965400/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
TypeError: is not a function typescript class
提问by Aaron
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.
谢谢。
回答by Nitzan Tomer
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 thisin 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, butin 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 method2can't be (easily) overriden, so beware of this implementation.
因为它method2不能(容易)被覆盖,所以要小心这个实现。

