Unable to verify Angular 5 identity

After authentication, the application should redirect to another page. However, despite successful authentication according to the logs, the redirection does not occur. What could be causing this issue?

auth.guard.ts:

import { Injectable }     from '@angular/core';
import {CanActivate, Router} from "@angular/router";
import {Angular2TokenService} from "angular2-token";

@Injectable()
export class AuthGuard implements CanActivate {

  constructor(private authTokenService:Angular2TokenService,
              private router:Router){}

  canActivate() {
    if (localStorage.getItem('currentUser')) {
        // logged in so return true
        return true;
    }

    // not logged in so redirect to login page
    this.router.navigate(['/sign_in']);
    return false;
}

}

auth.service.ts:

import { Injectable } from '@angular/core';
import {Angular2TokenService} from "angular2-token";
import {Subject} from 'rxjs/Subject';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import {Response} from "@angular/http";

@Injectable()
export class AuthService {

  userSignedIn$:Subject<boolean> = new Subject();

  constructor(private authService:Angular2TokenService) {
    this.userSignedIn$.next(this.authService.userSignedIn());
  }

  logOutUser():Observable<Response>{

    return this.authService.signOut().map(
        res => {
          this.userSignedIn$.next(false);
          return res;
        }
    );
  }

  logInUser(signInData: {email:string, password:string}):Observable<Response>{

    return this.authService.signIn(signInData).map(
        res => {
          this.userSignedIn$.next(true);
          return res
        }
    );

  }

   registerUser(signUpData:  {email:string, password:string, passwordConfirmation:string}):Observable<Response>{
    return this.authService.registerAccount(signUpData).map(
        res => {
          this.userSignedIn$.next(true);
          return res
        }
    );
  }

}

sign-in.component.ts:

import { Component, OnInit, Output, EventEmitter } from '@angular/core';
import { AuthService } from "../../services/auth.service";
import {Router} from "@angular/router";

@Component({
  selector: 'app-sign-in',
  templateUrl: './sign-in.component.html',
  styleUrls: ['./sign-in.component.css']
})
export class SignInComponent implements OnInit {

  signInUser = {
    email: '',
    password: ''
  };

  @Output() onFormResult = new EventEmitter<any>();

  constructor(private _router: Router, private authService:AuthService) { }

  ngOnInit() {}

  onSignInSubmit(){

    this.authService.logInUser(this.signInUser).subscribe(

        res => {
          if(res.status == 200){
            // loginForm.resetForm();
            this.onFormResult.emit({signedIn: true, res});
            this._router.navigate(['user_profile']);
          }
        },

        err => {
          console.log('err:', err);
          // loginForm.resetForm();
          this.onFormResult.emit({signedIn: false, err});
        }
    )

  }




}

sign-in.component.html:

<div class="main-content">
        <form (ngSubmit)="onSignInSubmit()" #f="ngForm" >


                <div class="row">

                  <div >
                    <input id="email"
                           type="email"
                           required
                           name='email' 
                           [(ngModel)]="signInUser.email" 
                           class="validate">

                    <label for="email">Email</label>
                  </div>


                  <div >
                    <input id="password" 
                           type="password" 
                           required  
                           name='password' 
                           [(ngModel)]="signInUser.password" 
                           class="validate">

                    <label for="password">Password</label>
                  </div>

                  <div >
                    <button type="submit" 
                    > 
                      Login </button>
                  </div>


                </div>

              </form>

</div>

Answer №1

You need to correct the path in user_profile by using the code snippet below:

 this._router.navigate(['/user_profile']);

Answer №2

To ensure your auth guard works correctly on the 'user_profile' path, make sure to store the 'currentUser' in localStorage. Failing to do so may result in the guard redirecting you back to the signin page.

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

Sequelize is not giving the expected model even after utilizing `include: [{ model: this.buildModel, required: true }]`

I've hit a roadblock trying to solve this problem. Despite my belief that I've correctly handled the migration, model definition, and query, I'm unable to retrieve the build in my iteration. Below are the models: SequelizeBuildModel.ts @Ta ...

What is the best way to bring two useStyles files into a single TypeScript file?

I am having an issue with finding a declaration file for the module 'react-combine-styles' even after I installed it using npm install @types/react-combine-styles. import React, { useState } from "react"; import useStyles from "./u ...

Using ngIf to locate a substring

<ul class="list-group" *ngFor="let head of channelDisplayHeads"> <li class="list-group-item" *ngFor="let channel of channelList" ngIf="channel.channel.indexOf('head') === 1"> <strong>{{ head }}</strong> ...

I'm encountering an issue where the 'switchMap' property is not recognized on the 'Observable<User>' type

I encountered an issue while attempting to run code in git bash. The problem arises from 'switchMap' not being executed and displaying the error message: "error TS2339: Property 'switchMap' does not exist on type 'Observable'" ...

Does SharePoint Online support the .webmanifest format? What is the process for creating a Progressive Web Application in SharePoint Online using a supported webmanifest file?

Currently, I am in the process of developing a Progressive Web Application for SharePoint Online by utilizing the Angular 8 PWA build. The service worker and application are running smoothly; however, I have encountered an issue with loading the webmanifes ...

Angular and Webpack combined to output the build project to the specified output path

In the process of integrating my Angular client-side application with a server-side written in Spring, I am seeking a way to build the UI project and store it in the /target directory within the backend portion for easy installation using Maven. My uncer ...

Unable to make a reference to this in TypeScript

In my Angular2 application, I have a file upload feature that sends files as byte arrays to a web service. To create the byte array, I am using a FileReader with an onload event. However, I am encountering an issue where I cannot reference my uploadService ...

What's the best way to show the calendar date in the mm-dd-yyyy format within an input search tag in Angular

I have implemented the <input class="input-group1 search" id="to" placeholder="dd-mm-yyyy" [(ngModel)]="toDate" value="" name="dp3" type="date"> in my code, which currently di ...

Failed to load module chunk: Please update to angular 7

I am encountering an issue with my application hosted on IIS after upgrading to Angular 7. The error message "Loading chunk module failed" indicates that instead of fetching files from the dist/ folder, it is attempting to fetch them from the root folder. ...

What is the best way to turn off template binding for a specific section of a template in Angular2?

Can someone help me figure out how to show the {{ name }} string in an Angular 2 template? Is there a way to turn off template binding for only a section of the template? Thanks in advance! ...

Importing libraries in TypeScript and JavaScript are not done in the same manner

As I create my own library, I aim for it to be compatible with both javascript and typescript. tsconfig.json { "compilerOptions": { "target": "es2017", "module": "commonjs", &qu ...

retrieve the initial subarray from the array using rxjs

Looking to extract the first array from a subarray, my current setup is as follows: Map: map; Map() { Service }); } This is the interface structure: export interface map { } Encountering an error message: ERROR TypeError: ...

Use ngFor to align items to the left in your design

I am working on a div element where I need to dynamically add inputs that should form a number with a specific format. To ensure the inputs start from the left, I have applied the justify-content-end class. HTML: <div class='row justify-content-end ...

Guide to utilizing Angular's translate i18n key as a dynamic parameter within HTML

Looking to pass an i18n translate service key as a parameter function on an HTML component. Attempted the following, but instead of getting the text, it's returning the key value. Created a variable assigned with the title in the component.ts file. ...

Callbacks are never fired in SQL Server because of the tedious connection

I have successfully connected to a SQL Server instance hosted in Azure through DBeaver and can browse all the data. After installing tedious with the following commands: npm install tedious npm install @types/tedious This is the exact code I am using: im ...

What is the reasoning behind TypeScript's decision to permit the omission of a function's return type?

After setting noImplicitAny to true in my tsconfig, I was surprised to find that I could still omit function return types. One instance is a getter function as shown below: get name() { return `${this.valueName} of ${this.suitName}`; } Inquiry 1: Can ...

Easy steps for importing node modules in TypeScript

I'm currently navigating the world of TypeScript and attempting to incorporate a module that is imported from a node module. I have chosen not to utilize webpack or any other build tools in order to maintain simplicity and clarity. Here is the struct ...

Ways to implement a component service interface in Angular

My goal is to create a component that enforces certain design guidelines, particularly focusing on the constructor. //cool-header.component.ts @Component({ selector: 'cool-header', moduleId: module.id, templateUrl: './header.compone ...

An error was encountered while parsing JSON data in Angular due to an unexpected token

I am currently working on implementing role-based authorization in my project. The goal is to hide certain items in the navigation bar based on the user's role. I encountered an error as shown below. How can I resolve this? service.ts roleMatch(a ...

Issues with Angular routing after upgrading to Angular 4

After making updates in this way, they can be found here To update on Linux/Mac: run the command npm install @angular/{common,compiler,compiler-cli,core,forms,http,platform-browser,platform-browser-dynamic,platform-server,router,animations}@latest type ...