Angular2 injected Router is undefined

前端 未结 1 856
粉色の甜心
粉色の甜心 2021-01-20 21:57

if I inject the router from @angular/router into a component and then use it, I get an error saying the cannot call navigateByUrl of undefined.

This is the component

相关标签:
1条回答
  • 2021-01-20 22:15

    You can use the arrow function to make sure you can still have a reference to this and it is LoginComponent instance:

    ....subscribe((data) => this.loginCallback(data));
    

    Another option is use bind method like:

    ....subscribe(this.loginCallback.bind(this));
    

    or in contructor:

    this.loginCallback = this.loginCallback.bind(this);
    

    One more option is using arrow function within your loginCallback:

    private loginCallback = (data: any) => {
      ...
    }
    
    0 讨论(0)
提交回复
热议问题