After calling the service, Angular 2 is unable to perform any actions within the subscribe method

I am struggling with what to do after authenticating my user. Once I receive the data, I want to redirect them to the appropriate page based on their role and display their name on that page. I have tried various methods, but it seems like when I try to call the router or a function, it's not in the same context. How can I resolve this issue?

Below is my login component code:

  import { Component, OnInit } from '@angular/core';
    import {User} from "../models/user";
    import {AuthenticationService} from "../services/authentication.service";
    import {Router} from "@angular/router";

    @Component({
      selector: 'app-login',
      templateUrl: './login.component.html',
      styleUrls: ['./login.component.css'],
      providers: [AuthenticationService]
    })
    export class LoginComponent implements OnInit {

      user: User = new User();
      result: any;

      constructor(private authenticationService: AuthenticationService,
private router: Router) {
      }

      loginAction() {
        this.authenticationService.login(this.user)
            .subscribe(function(result){
              this.result = result;
              console.log(this.result); // result : {token: "ABCDE....", "email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e195849295a195849295cf828e8c">[email protected]</a>", "username": "Jack James", role:"ADMIN"}
              this.doSth(); //Never called, likely due to different context 
               this.router.navigate(['home']); // router not being found
              // Need help with actions to redirect to another page and display currently logged-in user
            },
              err => {
                // Log errors if any
                console.log(err);
            });
      }

      doSth(){
        console.log("Do something");
      }

      ngOnInit() {
      }

    }

Answer №1

The issue lies in the following line of your code: .subscribe(function(result){ !!

When using the function() syntax, the this scope is lost!

To resolve this, you should use the arrow syntax () => ..

Here's how it should look: .subscribe((result) => {.

Now you can successfully utilize this.router.... :)

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

Oops! An unexpected error occurred: TypeError - Seems like _this.searchElementRef is not defined

I recently implemented the Google Place API in my project by following this tutorial. However, I encountered the following error: ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'nativeElement' of undefined The issue seems ...

Executing Multiple Requests Concurrently in Angular 5 using forkJoin Technique

Important Note The issue lies in the backend, not Angular. The requests are correct. In my Angular5 app, I am trying to upload multiple files at once using rxjs forkJoin. I store the requests in an array as shown in the code below. However, after adding ...

When receiveMessage is triggered, the FCM push notification fails to refresh the view

After following this helpful tutorial on Push Notifications with Angular 6 + Firebase Cloud Messaging, everything is working perfectly. I am able to receive notifications when using another browser. To ensure that my notification list and the length of no ...

What is the process for defining a series of tests for karma through code?

Currently, I am in the process of developing an Angular Test Explorer. The exciting part is that I can view all the tests and execute them collectively by leveraging the karma module as shown in this code snippet: public async runWithModule(): Promise&l ...

What is the best way to ensure that a div containing lengthy text wraps to the next line as if it were only text overflow?

Is there a way to make a div or span within another div act as text, causing overflow to shift to the next line? I'm unsure of which CSS properties would achieve this effect. I've attempted using overflow-wrap: break-word; word-break: break-al ...

Tips on showing validation error message through a tooltip when hovering over the error icon in Ionic

Currently, I have implemented bootstrap validation within my Ionic application and it is functioning correctly. The error icon appears within the textbox along with the error message below the textbox. However, I am interested in changing this setup so t ...

Utilizing server side parameters in Angular components with Kendo Grid

Recently, I've been utilizing the kendo grid alongside angular 4 and am now attempting to incorporate server-side custom pagination. The initialization of the Kendo grid occurs within a JavaScript method. However, one issue that has arisen is figuri ...

Issue with NgRx store: Incorrect parameter types being passed in reducer function

My goal is to implement a basic reducer, but I encountered an issue after updating app.module.ts with code I borrowed from [coursetro.com][1]. The error I received was perplexing. The error message stated that the function I attempted to pass as paramete ...

Encountering both a CORS error and data in Angular 7

My application is using Angular 7 for the front end and Node.js (express) for the backend. The cors module in the Node.js server.js file is implemented like this: var cors = require('cors') app.use(cors()); When making an API call from the fro ...

TypeScript is encountering difficulty locating a node module containing the index.d.ts file

When attempting to utilize EventEmitter3, I am using the following syntax: import EventEmitter from 'eventemitter3' The module is installed in the ./node_modules directory. It contains an index.d.ts file, so it should be recognized by Typescrip ...

Determine whether there is greater available space above or below a specific element within the DOM

I'm looking to create a dynamic layout where an input field is accompanied by a list in a div, positioned either above or below depending on available space. This setup needs to account for the fact that the input field could be located anywhere on th ...

The NG8002 error has occurred, as it is not possible to connect to 'matDatepicker' because it is not a recognized attribute of 'input'

I've come across an issue while working on my Angular 15 application with Angular Material. I'm trying to incorporate a date picker, but after adding the code snippet below, I encountered an error. <mat-form-field appearance="outline" ...

Is the window.location.href of a component not inside a router-outlet updated after a router redirect through a guard?

The navigation component I have is positioned outside of the router. It utilizes a reusable icon component that depends on absolute URLs to point to SVG icons, retrieved through a getter within the component: public get absUrl(): string { return windo ...

What is the best way to convert a date to ISO 8601 format using JavaScript? Are there any built-in functions or methods in

Currently, I am using this function to set the duration: const setDuration = () => { const currentDate = new Date(); const newDate = new Date(currentDate.getTime()); const year = newDate.getUTCFullYear(); const m ...

Looking to switch up the menu in Angular 6

Looking to toggle the side navigation bar, I have: Created a boolean variable toggle_menu set to true Added a function togg() on button click in the menu bar that sets the boolean value to false and toggles the div However, here's the iss ...

Ensuring accurate properties are sent to popup notifications

As a newcomer to a React & ASP.NET project, I am facing a challenge in displaying upload status notifications. The task may seem simple, but I need help in figuring out how to create popup notifications that indicate which files have been successfully uplo ...

Typescript in Firebase Functions organization

Struggling with typescript organization in my firebase functions. I'm fine keeping trigger functions in index.ts for now, but need help organizing other utility functions elsewhere. Current index.ts setup: import * as functions from 'firebase-f ...

We're sorry, the request was blocked due to a missing Access-Control-Allow-Origin header

Recently, while working on a blog application with the front end in react + typescript and backend in go iris, I encountered an issue when trying to fetch blog content using a get request. The backend was running on localhost:5000 and the node at localhost ...

"Converting to Typescript resulted in the absence of a default export in the module

I converted the JavaScript code to TypeScript and encountered an issue: The module has no default export I tried importing using curly braces and exporting with module.exports, but neither solution worked. contactController.ts const contacts: String[ ...

`Where can I find both the old and new values in Angular mat-select?`

Hello there. I am currently working with Angular 6 and Angular Material. I have an array of strings that I am displaying in a dropdown field using mat-select. I need to be able to track the previous value and the new value when a user selects different ele ...