首页 > 解决方案 > 如何在 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')

帮助!

标签: jqueryangular

解决方案


所以你需要像这样将它导入到你的模块中..

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']);
    });
}

推荐阅读