好吧,我又来了更多的 Angular 问题。对不起(?
问题是我试图在注册后重定向用户,但由于某种原因,我每次都收到下一个错误:
ERROR TypeError: "this.router is undefined"
基本上,我正在处理表单提交(工作正常(输入并将它们发布到我的 Laravel API,它接受它,执行注册并返回成功消息。无论哪种方式,我都无法使用下一段代码重定向用户(使用 Angular Router(:
onSubmit() {
this.authService.registerUser(this.user).subscribe(
response => {
let data = Object.assign(response.alert, this.denyControllConfig);
this.sweetAlert(data);
},
error => {
let data = {};
let errors = error.error.errors;
for (let key in errors) data[key] = errors[key][0];
// this.sweetAlert(data);
}
);
setTimeout(function () {
this.router.navigate(['login']);
}, 2000);
}
我已经在文件顶部导入了这样的 Rourter:
import { Router } from "@angular/router";
这是我的类构造函数:
constructor(
private router: Router,
private authService: AuthService
) { }
有什么问题吗?
您需要在代码中使用箭头函数才能使用this
setTimeout(() => {
this.router.navigate(['login']);
}, 2000);
我相信问题出在以下代码中:
setTimeout(function () {
this.router.navigate(['login']);
}, 2000);
在这种情况下,由于您使用的是匿名函数,因此this
关键字是函数本身的上下文。要解决此问题,请将其更改为:
setTimeout(() => {
this.router.navigate(['login']);
})
箭头函数的工作方式将允许this
成为类上下文而不是函数上下文。
您的setTimeout
必须使用箭头函数作为回调,以避免重新绑定this
的上下文。