I am attempting to perform a POST request using XMLHttpRequest and I would like to redirect to another component if the xhr request is successful.
Here is the code snippet:
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}]);
}
}
}
}
The code above ran successfully. However, my concern is, how can I redirect to the desired target in angular2 or JavaScript.
I utilized router.navigate
but Chrome displays the following error:
EXCEPTION: TypeError: Cannot read property 'navigate' of undefined
I also tested
window.location = '/sidenav/PreviousDetailsCmp';
but it did not work.