问题描述
我想在我的 Angular 项目的打字稿类中引用关键字this".但它不能使用.我总是收到我想要更改的变量未定义的错误.这是我的实现:
I want to reference the keyword "this" in a typescript class in my Angular project. But it cannot be used. I always get the error that the variable I want to change is not defined. Here is my implementation:
export class ContactComponent implements OnInit {
contactForm: FormGroup;
errorMsg:string = '';
redirect = "";
loggedIn(): void {
this.redirect = "dashboard";
console.log("success");
在我的 HTML 中,重定向变量像这样连接到 routerLink:
in my HTML the redirect variable is connected to a routerLink like this:
<a [routerLink]="redirect"></a>
我在其他函数中用其他变量尝试过这个,但总是有同样的错误.
I have tried this with other variables in other functions but had always the same error.
loggedIn 函数在另一个函数中作为success"参数被调用,如下所示:
The loggedIn function is called within another function as "success" parameter like this:
submitForm(): void {
DBEventProxy.instance().dbevent.login(this.contactForm['username'],
this.contactForm['password'], this.loggedIn, this.failed);
}
登录函数需要参数用户名、密码、成功函数、失败函数.
The login function needs the parameters username, password, success function, failfunction.
推荐答案
您需要将 loggedIn
绑定到正确的上下文.有几个选项:
You need to bind loggedIn
to the correct context. There are several options:
1) 将 loggedIn
定义为绑定函数:
1) define loggedIn
as bound function:
export class ContactComponent implements OnInit {
loggedIn = () = > {
this.redirect = "dashboard";
console.log("success");`
2) 使用 bind
export class ContactComponent implements OnInit {
contactForm: FormGroup;
errorMsg:string = '';
redirect = "";
loggedIn(): void {
this.redirect = "dashboard";
console.log("success");
submitForm(): void {
DBEventProxy.instance().dbevent.login(this.contactForm['username'],
this.contactForm['password'], this.loggedIn.bind(this), this.failed);
^^^^^^^^^^
}
3) 将 this.loggedIn
包装成一个箭头函数,这样可以保留上下文:
3) wrap this.loggedIn
into an arrow function that preserves context like this:
this.contactForm['password'], () => this.loggedIn(), this.failed);
而且您可能想对 this.failed
做同样的事情.阅读有关 bind
和箭头函数的更多信息 这里
And probably you want to do the same for this.failed
. Read more about bind
and arrow functions here
这篇关于“这个"不能在打字稿功能(Angular)中使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!