jquery - 如何在 Angular 4 的 $.post 中访问 router.navigate()?
问题描述
Typescript 和 Angular 4 的新手。
下面的Continue()
函数在(click)
html 模板中的事件期间触发。如您所见,AJAX 帖子是用 jquery 制作的,一切都按预期工作。但是,在后端成功后,我需要转到另一个页面并且router.navigate()
找不到。
import { Component, OnInit, Input } from '@angular/core';
import * as jQuery from 'jquery';
@Component({
selector: 'app-signup',
templateUrl: './signup.page.html',
styleUrls: ['./signup.page.scss']
})
export class SignupPage implements OnInit {
@Input() email: string;
constructor() {}
ngOnInit() {}
Continue() {
$.post( 'https://mydomain/lgn',{email: this.email}, function(data) {
/* problem here */
this.router.navigate(['/vemail']);
});
}
}
浏览器控制台错误:
TypeError: undefined is not an object (评估 'this.router.navigate')
帮助!
解决方案
所以你需要像这样将它导入到你的模块中..
import { Router } from @angular/router;
然后你需要在你的构造函数中声明它,
constructor(public router: Router){}
那么你就可以使用this.router.navigate()
也由于范围this
不起作用,所以在您的 jquery 调用之前执行此操作
const that = this
然后改为这样做
that.router.navigate();
所以你的电话看起来像这样
Continue() {
const that = this;
$.post( 'https://mydomain/lgn',{email: this.email}, function(data) {
/* problem here */
that.router.navigate(['/vemail']);
});
}
基本上角度在箭头函数上运行,所以当你使用 ES5 函数时它会中断this
或者正如 Simon K 指出的那样,您也可以轻松地做到这一点,并使用箭头函数而不是常规函数
Continue() {
$.post( 'https://mydomain/lgn',{email: this.email}, data => {
/* problem here */
this.router.navigate(['/vemail']);
});
}
推荐阅读
- reactjs - 如何为 react 和 django 应用程序编写 bitbucket-pipelines.yml 以部署在 heroku 上
- python - Python 字符串到文件
- python - 如何在 Discord.py 中按 ID 踢用户
- python - scapy 嗅探 ZigBee 流量,不检测 ZigBee 层
- vba - 从模板创建后如何使新文档可见?
- java - 如何修改我的信用卡验证程序以仅在我最后一个检查卡类型的函数中检查有效数字?
- sql - SQL 语法错误:“缺少右括号”
- ruby - 如何防止硒无头中的虚假用户代理检测?
- javascript - 如何获取层次结构中所有节点的路径
- amazon-web-services - AWS EC2 CLI 如何获取列表 EC2 实例 - 限制输出