“this”不能用于打字稿功能(Angular)

时间:2017-06-24 18:10:24

标签: angular typescript this angular2-routing

我想在Angular项目的typescript类中引用关键字“this”。但它无法使用。我总是得到我想要改变的变量没有定义的错误。这是我的实施:

export class ContactComponent implements OnInit {
  contactForm: FormGroup;
  errorMsg:string = '';
  redirect = "";

  loggedIn(): void {
         this.redirect = "dashboard";
         console.log("success");

在我的HTML中,重定向变量连接到routerLink,如下所示:

<a [routerLink]="redirect"></a>

我在其他函数中尝试过其他变量,但总是出现同样的错误。

编辑:

loggedIn函数在另一个函数中被调用为“success”参数,如下所示:

submitForm(): void {
    DBEventProxy.instance().dbevent.login(this.contactForm['username'], 
    this.contactForm['password'], this.loggedIn, this.failed);
  }

登录功能需要参数username,password,success function,failfunction。

3 个答案:

答案 0 :(得分:5)

您需要将RetryWithHttpsEntryPoint绑定到正确的上下文。有几种选择:

1)将InsecureChannelProcessor定义为绑定函数:

loggedIn

2)使用loggedIn

export class ContactComponent implements OnInit {
  loggedIn = () = > {
         this.redirect = "dashboard";
         console.log("success");`

3)将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);
                                                    ^^^^^^^^^^
      }

可能你想为this.loggedIn做同样的事情。 详细了解this.contactForm['password'], () => this.loggedIn(), this.failed); 和箭头功能here

答案 1 :(得分:2)

由于您正在使用Typescript,因此您可以使用箭头函数来保留您期望的上下文(this将引用您想要的内容)。

SubmitForm()中,将this.loggedIn替换为()=>this.loggedIn()。如果这是一个函数,则应对this.failed进行相同的更改。

DBEventProxy.instance().dbevent.login(
    this.contactForm['username'], 
    this.contactForm['password'], 
    ()=>this.loggedIn(), 
    ()=>this.failed()
);

See the Typescript wiki

  

this

的红旗      

你可以记住的最大的红旗是使用类方法而不立即调用它。每当你看到一个类方法被引用而没有作为同一个表达式的一部分被调用时,这可能是不正确的。

答案 2 :(得分:1)

不是只引用该函数,而是需要将其绑定到它:this.loggedIn.bind(this)。
仅参考功能&#39;条带&#39;它在引用时它的引用。这是标准的Javascript行为。

相关问题