Organizing the AuthGuard(canActivate) and AuthService code in Angular 2

After working on my current code, I have encountered an issue when routing to a page with the canActivate method. I was able to retrieve authentication data from the server using the following setup

auth.guard.ts (version 1)

import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from '@angular/router';
import { Observable } from 'rxjs/Rx';
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import { Headers, RequestOptions } from '@angular/http';

@Injectable()
export class AuthGuard implements CanActivate {
    constructor(private router: Router, private http: Http) { }

    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
        let headers = new Headers({ 'Content-Type': 'application/json' });
        let options = new RequestOptions({ headers: headers });

        return this.http.post('/api/authenticate', options )
            .map(res => res.json())
            .map((res) => {
                if (res.response) {
                    return true;
                } else {
                    this.router.navigate(['/register']);
                    return false;
                }
            });
    }
}

I attempted to separate the code inside canActivate into auth.service.ts as shown below. However, it seems that the process does not wait for the HTTP request to complete before returning

auth.service.ts

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import { Headers, RequestOptions } from '@angular/http';
import 'rxjs/add/operator/map';
import { Observable } from 'rxjs/Observable';

@Injectable()
export class AuthService {
    constructor(private http: Http) { }

    authenticate() :Observable<any>{
        let headers = new Headers({ 'Content-Type': 'application/json' });
        let options = new RequestOptions({ headers: headers });

        return this.http.post('/api/authenticate', { options })
            .map(res => res.json())
    }
}

auth.guard.ts (version 2)

    import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from '@angular/router';
import { Observable } from 'rxjs/Rx';
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import { Headers, RequestOptions } from '@angular/http';
import { AuthService } from './auth.service';

@Injectable()
export class AuthGuard implements CanActivate {
constructor(private authService: AuthService, private router: Router, private http: Http) { }

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
if(this.authService.authenticate()){
return true;
}else{
this.router.navigate(['/register])
return false;
}
}
}

Can anyone point out what I am missing in this implementation?

Answer №1

authentication.guard.ts (v3)

class AuthenticationGuard implements CanActivate {
    constructor(private authenticationService: AuthenticationService, private routerService: RouterService, private httpService: HttpService) { }

    canActivate(routeInfo: ActivatedRouteSnapshot, stateInfo: RouterStateSnapshot) {
        return this.authenticationService.authenticateUser().map((response) => {
            if (response.data) {
                return true;
            } else {
                this.routerService.navigateTo(['/signup']);
                return false;
            }
        });

    }
}

The code above will link your observables together. However, there seems to be an issue with the logic -- if(response.data) {return true}. This condition does not distinguish between 'existing user logged in' and 'non-existing user'. You will need to rectify this.

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

The absence of @angular/compiler in the bundle file is causing an issue with Angular es

I've developed a shell application that operates using and https://github.com/systemjs/systemjs to manage its various micro-frontends. Recently, I created a new Angular application and aimed to integrate it with the esBuild builder tool. Upon runni ...

You cannot assign an array of 'Contact' objects to a single 'Contact' parameter

During the development process, I encountered an error while trying to add a new contact. The error message states: Error: src/app/contacts/contacts.component.ts:32:28 - error TS2345: Argument of type 'Contact[]' is not assignable to parameter o ...

Issues with the 'GET' request functionality on the deployed Angular project

I am attempting to run an Angular project that I have built. After copying the folder generated from 'ng build' and placing it in the directory where my back end code (using express) is located, I am trying to run it on my laptop at port 3000. Wh ...

Is it possible to launch my MEAN application on a personal server running Debian and nginx?

After successfully creating my first app using the MEAN stack (Mongo, Express, Angular 2/4, Node), I am facing an issue where it only functions on my local environment. When I initiate the client (frontend) part with 'ng serve,' it works on local ...

Disabling sound feature in the "mat-video" npm package

Currently, I've implemented the mat-video package (npm i mat-video) in my angular application to facilitate video playback. It's been working quite well. <mat-video style="min-height: 30%" quality="false" title="My Tutorial Title" loo ...

Angular - Implementing validation for maximum character length in ngx-intl-tel-input

Utilizing the ngx-intl-tel-input package in my Angular-12 project multistep has been quite promising. Below is a snippet of the code: Component: import { SearchCountryField, CountryISO, PhoneNumberFormat } from 'ngx-intl-tel-input'; expor ...

Generic interface function in Typescript

Having some issues with my generic interface function. Seems like I've been staring at it for too long... Can someone please point out what I'm doing wrong? This is my Interface: export interface Compareable<T> { equals(compareable:T) ...

Troubleshooting cross-origin resource sharing header issue between Django backend and Angular frontend

After implementing CORS on my Django backend using the django-cors-headers package and following the steps outlined in the documentation at https://github.com/OttoYiu/django-cors-headers, I performed these specific actions: pip install django-cors-header ...

Angular index.html file can include a conditional script

I am currently working on an Angular project, where the index.html serves as the main entry point for the application, just like in any other Angular project. This file contains important links and configurations. Within the HTML code snippet below, you w ...

Issue: Unable to resolve all parameters for LoginComponent while implementing Nebular OAuth2Description: An error has occurred when attempting to

I have been attempting to utilize nebular oauth in my login component, following the documentation closely. The only difference is that I am extending the nebular login component. However, when implementing this code, I encounter an error. export class Lo ...

After deploying to Heroku, cal-heatmap encounters errors despite functioning correctly in a local environment

I successfully implemented a cal-heatmap instance in my Angular 2 (angular-cli) project locally, but when I deployed the project to Heroku, I encountered some errors that prevent the cal-heatmap from displaying. https://i.stack.imgur.com/8gY90.png The er ...

Having trouble deleting a component from an array in React?

I am facing an issue with my array and component functions. Each component has a handleRemove function that is supposed to remove the selected component from the array. However, the function is not working as expected. Instead of deleting just the selected ...

Having trouble retrieving form values in Typescript React, only receiving HTML tag as output

I am having an issue with retrieving the form value to my useRef hook as it returns the HTML tag of the form instead. To solve this, I attempted to specify the type HTMLFormElement inside the chevrons and set null as the initial value for my useRef hook. ...

An unexpected error has occurred in Angular 2 while referencing the service proxy with code asd:18. The error message is: (SystemJS) Unexpected token < SyntaxError: Unexpected token

Forgive me for asking what may seem like a silly question. I am a newcomer to Angular 2 and encountering some problems with the API that my app is utilizing. The consumed Web API is located within the following folder structure: - src - app - Regist ...

Unable to append item to document object model

Within my component, I have a snippet of code: isLoaded($event) { console.log($event); this.visible = $event; console.log(this.visible); this.onClick(); } onClick() { this.listImage = this.imageService.getImage(); let span = docu ...

The deletion of property '1' from the [object Array] is not possible

How to Retrieve a List in My Components Using Input : @Input() usersInput: Section[]; export interface Section { displayName: string; userId: number; title: number; } Here is the Value List : 0: displayName: "بدون نام" ...

Trigger refetchQueries post-execution of a mutation operation

In the past, I executed a mutation in a similar manner as shown below: export const useEditLocationName = () => { const [editFavoriteLocationName] = useEditFavoriteLocationNameMutation({ refetchQueries: [{ query: GetMyFavouritePlacesDocument}], ...

Passing parameters in React classes is a crucial aspect of creating

Within a project I am currently working on, there is a const defined for the page header which takes in parameters and utilizes the information: interface UserProps { user?: { name: string, image: string }, loading?: boolean, error?: E ...

Refreshing the page causes TypeScript Redux to lose its state

custom/reducer/shoppingReducer.ts import { createSlice, PayloadAction } from "@reduxjs/toolkit"; import { ShoppingReducerInitialState } from "../../types/reducer-types"; import { ProductItem, ShippingDetails } from "../../types/typ ...

Are there type declarations in TypeScript for the InputEvent?

Wondering if there is a @types/* module that offers type definitions for the InputEvent object? For more information about InputEvent, you can visit this link. ...