How can I utilize Javascript XMLHttpRequest to redirect to a different component in Angular 2?

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.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Suggestions for Deleting Previous Polylines When Adding a New Path

Currently, I am working on a project in Angular that involves using Leaflet map to display data with JSON coordinates for flight paths. The issue I am facing is that when the data updates, the polyline path on the map gets duplicated. I have tried variou ...

Add elements to an array following an AJAX request

On my .cshtml page, I have the following script: $(function () { var tempArray = []; var tbValue = $('#tb1').val(); $.ajax({ url: "/ControllerName/getdata", dataType: 'json', ...

Where does tsc retrieve its definitions from when utilizing npm definitions?

After transitioning from using typings to just relying on npm, I noticed that the @types directory in node_modules is present, but there are no additional files required. Previously with typings, I always had to include the index.d.ts file within the typi ...

Having difficulty reaching the specified route ID in Angular app

I'm encountering an issue when attempting to navigate to a route with an ID argument using the router. Here's the code snippet from my component: import { Router } from '@angular/router'; ... constructor(private router: Router) { } .. ...

What is the best approach to dealing with "Cannot <METHOD> <ROUTE>" errors in Express?

Here is a simple example to illustrate the issue: var express = require('express'); var bodyparser = require('body-parser'); var app = express(); app.use(bodyparser.json()); app.use(errorhandler); function errorhandler(err, req, res, ...

Unable to populate ng2 piechart with received data from HTTP response

Below is the HTML markup I've used to display a pie chart from the NG2-Chart library, which has a dependency on chart.js: <h2>Home</h2> <div style="display: block"> <canvas baseChart class="chart" [data]="pieChart ...

Shared codes are compatible with both C and Javascript programming languages

Within the scope of this project, data will be retrieved from the server in either JSON or XML format. There are two separate client applications that will handle the data processing, with one being web-based and written in JavaScript, while the other is ...

Dynamic Angular component loading with lazy loading

In my Angular 4.1.3 project, I am currently developing a mapping application that incorporates lazy-loading for various tool modules. At present, the tools are loaded within the map using a router-outlet. However, I now need to expand this functionality to ...

Tap and hold with Zepto

I've been on the hunt for a Zepto plugin that can handle a longClick event. While Zepto already supports longTap, which is perfect for mobile devices, I need something specifically for desktop browsers when a user clicks and holds. It's also impo ...

Sending data with the request body using Express and Passport

I've created a login application using Express and Passport, but I'm having trouble directing the user to their specific user profile page. The goal is for users to fill out an HTML form and then be redirected to their own profile page (which dif ...

Adjust the camera in threejs to be positioned inside a different object

My goal is to adjust the camera controlled by trackballControl to match the position of an object. Currently, it's functioning correctly but as demonstrated in this example, each time the camera changes its position, the z value also changes, which i ...

Performing tasks when a component is fully loaded in Vue.js Router

I am currently working on a project involving a single-page application built with Vue.js and its official router. For this project, I have set up a menu and a separate component (.vue file) for each section that is loaded using the router. Inside every c ...

The table is not properly displaying the data even though it is stored in the array and can be seen in the browser console. What could be causing this issue with my

<tr *ngFor="let animal of readAnimal"> <th scope="row">{{ animal.id }}</th> <td>{{ animal.name }}</td> <td>{{ animal.description }}</td> <td>{{ animal.creat ...

Encountering a syntax error with JSON.parse() when using MVC 4 Razor with Jquery Ajax

I am encountering an issue with my MVC 4 application login page. I am attempting to utilize a jQuery ajax request to my login controller to check if the user exists. Here is the snippet of my jQuery code: $(document).ready(function () { $("#btnSub ...

The term "containerName" in SymbolInformation is utilized to represent the hierarchy of

In my quest to make the code outline feature work for a custom language, I have made progress in generating symbols and displaying functions in the outline view. However, my next challenge is to display variables under the respective function in the outlin ...

Mastering Cookies in Javascript

I have been exploring the world of cookies in Javascript and decided to create an experimental log-in page. The page is fully functional, but I am interested in displaying the user's username and password using cookies. Is this possible with Javascrip ...

Utilizing dynamic content to pass arguments to JavaScript functions

I'm facing a challenging issue that is causing me frustration. While browsing through this platform, I found some potential solutions but encountered a roadblock in implementing them successfully. My current project involves developing an e-commerce p ...

I am facing a problem with React Hooks useRef where I am unable to retrieve the updated state value

Trying to use useRef with React hooks, I encountered an issue where the state of the child component changes when calling the setAccountVal method, but upon alerting the value it remains as "Ege". Any ideas on how to resolve this? import React, { useS ...

Using deconstruction in exporting as default

As I was diving into a new codebase, I stumbled upon this interesting setup: //index.js export { default } from './Tabs' export { default as Tab } from './Tab' //Tab.js export default class Tab extends Component { render() => &ap ...

Unlimited Cycle using Vue Router Global Precautionary Measures

Currently, I am facing an issue with redirecting users using Firebase Auth and Vue Router. The problem arises when the Router redirects the user to '/' as it results in a blank white screen on the website. I am aware that there is an error in m ...