this.router 在 AngularJS 中未定义 2

this.router is undefined in AngularJS 2

这是我注册用户并重定向到主页的方法:

onSubmit(){
    this.userService.createUser(this.user).subscribe(function (response) {
            alert('Successfully registered');
            localStorage.setItem('token', response['token']);
            this.router.navigate(['Home']);
        }, function (err) {
            console.log(err);
        }
    );
}

在它上面,我有这个构造函数:

constructor(private router: Router, private userService: UserService){}

我在主成分中添加了ROUTER_PROVIDERS

providers: [
    ROUTER_PROVIDERS,
    HTTP_PROVIDERS
]

当我尝试注册用户时,出现此错误:

TypeError: Cannot read property 'navigate' of undefined

我做错了什么?

您需要在代码中使用箭头函数才能使用 "contextual this"(对应于您的组件实例):

onSubmit(){
  this.userService.createUser(this.user).subscribe((response) => { // <---
        alert('Successfully registered');
        localStorage.setItem('token', response['token']);
        this.router.navigate(['Home']);
    }, (err) => { // <---
        console.log(err);
    }
  );
}