Angular2如何使用Javascript XMLHttpRequest重定向到另一个组件?

时间:2016-03-21 06:43:00

标签: javascript typescript xmlhttprequest angular

我正在尝试使用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';,但它不起作用。

1 个答案:

答案 0 :(得分:2)

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

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

应该是

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

有关详细信息,请参阅https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Functions/Arrow_functions