[英]Typescript TypeError: ......toDateString is not a function
[英]TypeError: is not a function typescript class
我在打字稿类中收到以下错误,无法理解原因。 我所做的就是尝试调用传递令牌的辅助函数。
错误:
发布错误: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);
}
}
我是打字稿的新手,所以我确定我错过了一些非常简单的东西。 任何帮助都会很棒。
谢谢。
它应该是(使用Function.prototype.bind ):
return this.http.post(url + 'login', body, options)
.map(this.handleData.bind(this))
.catch(this.handleError.bind(this));
或者(使用箭头函数):
return this.http.post(url + 'login', body, options)
.map((res) => this.handleData(res))
.catch((error) => this.handleError(error));
发生的情况是您传递了对方法的引用,但它没有绑定到特定的this
,因此当执行该方法时,函数体中的this
不是类的实例,而是执行该方法的作用域。
这些中的每一个都有助于为this
保持正确的上下文,但以不同的方式。
另一种选择是:
export class Authenticate {
...
private handleData = (res: Response) => {
...
}
private handleError = (error: any) => {
...
}
}
通过这种方式,“方法”已经被绑定,但在这种情况下,它们不会成为原型的一部分,实际上将成为函数类型的属性。
例如:
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
不能(容易)被覆盖,所以要注意这个实现。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.