【问题标题】:Angular2 How to redirect to another component using Javascript XMLHttpRequest?Angular2如何使用Javascript XMLHttpRequest重定向到另一个组件?
【发布时间】:2016-07-07 14:00:57
【问题描述】:

我正在尝试使用 XMLHttpRequest 发出 POST 请求,如果 xhr 请求成功,我想重定向到另一个组件。

这是我的代码:

import {Component, Inject, Injectable, OnInit} from 'angular2/core'
import {FORM_DIRECTIVES, NgForm, ControlGroup, FormBuilder, Control, CORE_DIRECTIVES, NgIf} from 'angular2/common'
import {HTTP_PROVIDERS, Http} from 'angular2/http'
import {ROUTER_DIRECTIVES, Router} from 'angular2/router'

export class StudentAdmissionForm{
    constructor (public router: Router){
    }

    makeFileRequest(data){

          var url = this.base_path_Service.base_path_student()+"student/";

          return new Promise((resolve, reject) => {

               var formData: any = new FormData(); 
               var xhr = new XMLHttpRequest();

               formData.append("image", this.studentDetails.image);           
               formData.append("first_name",this.studentDetails.first_name);
               formData.append("middle_name",this.studentDetails.middle_name);

               console.log(formData);  

                xhr.open("POST", url, true);
                xhr.setRequestHeader("Authorization", 'Bearer ' + localStorage.getItem('id_token')); 
                xhr.send(formData);
                xhr.onreadystatechange=function() 
                    {
                        console.log("status " + xhr.status);
                        if(xhr.readyState === XMLHttpRequest.DONE && xhr.status == 201){
                            toastr.success('Created !');
                            var res = JSON.parse(xhr.responseText);
                            this.router.navigate(['../PreviousDetailsCmp', {first_name:res.student_id, student_id:res.id}]);
                        }

                    }
    }
}

以上代码成功执行。但我的问题是,我可以在 angular2 或 javascript 中做什么来重定向到目标。

我使用了router.navigate,但 chrome 显示以下错误:

EXCEPTION: TypeError: Cannot read property 'navigate' of undefined

我也试过window.location = '/sidenav/PreviousDetailsCmp';,但它不起作用。

【问题讨论】:

    标签: javascript typescript xmlhttprequest angular


    【解决方案1】:

    您需要使用=> 而不是function 否则this. 不再指向您的组件类

    xhr.onreadystatechange=function(){ ... } 
    

    应该是

    xhr.onreadystatechange => () { ... }
    

    更多详情请见https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Functions/Arrow_functions

    【讨论】:

      猜你喜欢
      • 2021-02-26
      • 2022-01-24
      • 1970-01-01
      • 1970-01-01
      • 2016-12-07
      • 2017-06-13
      • 1970-01-01
      • 2018-09-11
      • 2021-12-09
      相关资源
      最近更新 更多