gpt4 book ai didi

jquery - 如何在 Angular 4 中的 $.post 中访问 router.navigate() ?

转载 作者:行者123 更新时间:2023-12-01 03:59:33 24 4
gpt4 key购买 nike

Typescript 和 Angular 4 新手。

下面的 Continue() 函数在 html 模板中的 (click) 事件期间触发。正如您所看到的,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 (evaluating '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']);
});
}

基本上, Angular 在箭头函数上运行,因此当您使用 ES5 函数时,它会破坏 this

或者正如 Simon K 指出的那样,您也可以轻松地做到这一点,并使用箭头函数而不是常规函数

Continue() {
$.post( 'https://mydomain/lgn',{email: this.email}, data => {
/* problem here */
this.router.navigate(['/vemail']);
});
}

关于jquery - 如何在 Angular 4 中的 $.post 中访问 router.navigate() ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51605012/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com