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);
}
);
}
相关文章:
- $window.ga在AngularJS事件中未定义
- this.router在AngularJS 2中未定义
- AngularJS指令出错-无法读取属性'编译'的未定义
- AngularJS指令单元测试中未定义的函数
- angularjs无法读取未定义的属性then
- AngularJS和promise值在调用本地函数时的效果-未定义
- AngularJS:'$范围未定义'
- Angularjs-NgTable在重新加载时未定义
- AngularJS-参数'菜单Ctrl'不是函数,未定义
- AngularJs无法读取属性“”;UpdateTime”;的未定义
- 未定义的控制器AngularJS
- AngularJS ng repeat显示原型函数未定义
- angularjs-ui路由器解析工厂未定义
- Angularjs类型错误:无法读取属性'GET()'的未定义
- AngularJs 检查是否未定义和空的最佳实践
- AngularJS:无法读取未定义的属性 ''
- 范围变量在函数内部未定义 - AngularJS
- 仅在未定义AngularJS时通过
- 自变量'controllerLogin'不是函数,未定义-AngularJs,因果报应测试
- 控制器未定义AngularJS