问题
As the title explains it, the router
object become undefined when it's called inside a subscribe
member.
Let me show you some code:
export class AuthComponent implements OnInit {
password = '';
email = '';
constructor(
private _router: Router,
private authService: AuthService
) { }
sendLogin(): void {
this.authService.login(this.email, this.password)
.subscribe(function(token){
console.log("Success Response" + token)
this.token = token
// TOKEN Here is good
// now I want to change my page, but
// _router -> undefined
this._router.navigate(['/dashboard']);
},
error => console.log(error));
}
the method sendLogin()
is called when submitting a form.
every varibales from the form are good.
The process reach the subscribe
perfectly, but then
this._router.navigate(['/dashboard']);
gives me :
EXCEPTION: Cannot read property 'navigate' of undefined
any ideas ?
回答1:
You have to use an arrow function to preserve the this
context.
sendLogin(): void {
this.authService.login(this.email, this.password)
.subscribe( token => {
console.log("Success Response" + token)
this.token = token
// TOKEN Here is good
// now I want to change my page, but
// _router -> undefined
this._router.navigate(['/dashboard']);
},
error => console.log(error));
}
回答2:
To avoid arrow function, you can use bind
to bound the this
context.
// ...
this.authService.login(this.email, this.password)
.subscribe(function(token){ //.. your code }.bind(this),
error => console.log(error));
} // ...
来源:https://stackoverflow.com/questions/40281375/angular2-router-become-undefined-in-subscribe-method