2016-03-21 96 views
1

我正在嘗試使用XMLHttpRequest進行POST請求,如果xhr請求已成功,我想重定向到另一個組件。Angular2如何使用Javascript XMLHttpRequest重定向到另一個組件?

這裏是我的代碼:

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';但它不工作。

回答

相關問題