我在 typescript 类中遇到以下错误,无法理解原因。我所做的只是尝试调用传递 token 的辅助函数。
错误:
post error: TypeError: this.storeToken is not a function(…)
类:
/**
* 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);
}
}
我是 typescript 的新手,所以我确定我错过了一些非常简单的东西。任何帮助都会很棒。
谢谢。
最佳答案
它应该是(使用 Function.prototype.bind ):
return this.http.post(url + 'login', body, options)
.map(this.handleData.bind(this))
.catch(this.handleError.bind(this));
或者(使用 arrow functions ):
return this.http.post(url + 'login', body, options)
.map((res) => this.handleData(res))
.catch((error) => this.handleError(error));
发生的事情是你正在传递一个对你的方法的引用,但它没有绑定(bind)到特定的 this
,所以当方法被执行时,函数体中的 this
不是类的实例,而是执行方法的范围。
它们中的每一个都有助于为 this
保持正确的上下文,但方式不同。
编辑
另一种选择是:
export class Authenticate {
...
private handleData = (res: Response) => {
...
}
private handleError = (error: any) => {
...
}
}
在这种情况下,“方法”已经被绑定(bind),但是在这种情况下,它们不会成为原型(prototype)的一部分,实际上只会成为函数类型的属性。
例如:
class A {
method1() { }
method2 = () => {}
}
编译为:
// es5
var A = (function () {
function A() {
this.method2 = function () { };
}
A.prototype.method1 = function () { };
return A;
}());
// es6
class A {
constructor() {
this.method2 = () => { };
}
method1() { }
}
因为 method2
不能(轻易)覆盖,所以要小心这个实现。
关于javascript - 类型错误 : is not a function typescript class,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40965400/