What is preventing the value from changing in auth.guard?

I am encountering an issue with the variable loggined, which I modify using the logTog() method. When I call this method, a request is made to a service where the current result is passed to auth.guard. However, in the console, it displays "undefined". Can anyone help me understand why this is happening and how it can be resolved?

Here is the code for AppComponent:

export class AppComponent implements OnInit {
    loggined: boolean = false;

    constructor(private galleryService: GalleryService) {}
    
    ngOnInit() {
        this.logTog();
    }
    
    logTog(): void {
        this.loggined = !this.loggined;
        this.galleryService.auth(this.loggined);
    }
}

Code for the Service:

    auth(log:boolean):boolean {
        console.log(log);
        return log;
    }

AuthGuard Code:

 export class AuthGuard implements CanActivate, OnInit {
  constructor(private galleryService: GalleryService) {}
  canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
    return this.galleryService.auth();
  }
  ngOnInit() {

  }
}

Answer №1

If you want to access the value of this.loggedIn in both the AppComponent and AuthGuard, consider creating a service for it. Instead of defining the this.loggedIn variable in the AppComponent, define it within the service.

LoggedInService

import { Injectable } from '@angular/core';

@Injectable()
export class LoggedInService {

  constructor(
    private router: Router
  ) { }

  private loggedIn;

  setLoggedIn(data) {
   // Set the value of this.loggedIn to true or false based on your requirements 
  }

  getLoggedIn() {
   return this.loggedIn;
  }

}

App.component.ts

export class AppComponent implements OnInit {


  constructor(private galleryService: GalleryService,
            private loggedInService: LoggedInService
  ) {}

  ngOnInit() {
    this.logToggle();
  }

  logToggle(): void {
    this.loggedInService.loggedIn = !this.loggedInService.loggedIn;
    this.galleryService.auth(this.loggedInService.loggedIn);
  }
}

The authentication file remains the same depending on your logic

//Same code

guard.ts

export class AuthGuard implements CanActivate, OnInit {
  constructor(private galleryService: GalleryService,
              private loggedInService: LoggedInService
  ) {}
  canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
    return this.galleryService.auth(this.loggedInService.loggedIn);
  }
  ngOnInit() {

  }
}

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

JavaScript/jQuery: Retrieve the correct header for every element

Looking at the given HTML structure (which is just an example and may not be entirely logical): <div id="wrapper"> <h3>First Heading</h3> <div class="row"><div class="col-12"><p class=& ...

Using rxjs for exponential backoff strategy

Exploring the Angular 7 documentation, I came across a practical example showcasing the usage of rxjs Observables to implement an exponential backoff strategy for an AJAX request: import { pipe, range, timer, zip } from 'rxjs'; import { ajax } f ...

I am working on a project where I have a parent component that contains a textarea element. My goal is to dynamically adjust the height of this textarea

Is there a way to adjust the size of a textarea component in a child component? textarea.html <textarea style = "height"=150px></textarea> // The height is defined globally here xyz.html <app-textarea></app-textarea> // Looking ...

Tips for continuing to write to the same CSV file without starting over

Currently, I am utilizing a nodejs package to write data to a CSV file every minute. The initial creation of the file and the first write operation work fine. However, when attempting to write to the same file again, I encounter an error in nodejs. Despite ...

How to create a responsive image that appears over a button when hovering in Bootstrap?

My goal is to display an image over a button when hovering. I've tried adding the .img-responsive class in Bootstrap while including the image in the HTML, but it's not working as expected with my current method of loading images. The buttons the ...

Encountering problems when trying to open .dialog using JQuery

Hello everyone! I have an interface where, after a user logs in, their information is checked. If the user has not read the Terms of Service (TOS), then a dialog box should open. However, I am facing an issue as the dialog box never opens. Here is the cod ...

Modifying the $locale setting in ui-router

My Goal and Approach Within our AngularJS application, we utilize angular-ui-bootstrap for datepickers. Our aim is to localize the datepickers based on the user's locale. However, dynamically changing the locale in AngularJS poses a challenge due to ...

Distinguishing between a video or image when uploading files in JavaScript

I've been researching whether JavaScript can determine if a file is a video or an image. However, most of the information I found only shows how to accept these types using the input tag. What I really need is for JS to identify the file type and the ...

Setting up Karma configuration to specifically exclude nested directories

When unit testing my Angular 2 application using Karma, I encountered an issue with my directory structure: └── src/ ├── index.js ├── index.js.text ├── index.test.js ├── README.txt ├── startuptest.js ...

How to return the same value as the input value in Vue before the action is completed

When creating a component and module for functionality X while using Vuex for state management, the code initially works fine. However, after the first insertion, the Getter function consistently returns the previous input value before the action is commit ...

Utilizing the Flex property on the parent div ensures that all child elements receive an equal width

I am currently working on a messaging application and I want the layout to be similar to Twitter or Whatsapp. Specifically, I want the messages from the person the user is chatting with to appear on the left side, while the user's own messages should ...

The function buf.writeBigUInt64BE is not recognized as a valid function and returns an undefined error

I'm attempting to implement the code below on my React Native iOS device: import { Buffer } from "buffer"; const buf = Buffer.alloc(8) buf.writeBigUInt64BE(BigInt(123), 0) const value = buf.readBigUInt64BE(0) console.log(value) However, I&a ...

Transferring data from SocketIO to Vue.js

Is there a way to effectively transfer data results received from socketIO to the Vue instance? Below is my current code implementation: let socket = io(); let users; socket.on('user-connected', (data) => { users = data.count; }); socket ...

Use the knockout textInput plugin in combination with the maskedinput plugin

Is there a simple way to use data-bind="textInput: aProperty" and apply an input mask or automatic formatting while the user is typing? Although using the masked input plugin somewhat works, it results in losing the real-time updates that Knockout's ...

Widget for navigating through Youtube videos

I am currently working on creating a widget that allows users to navigate a YouTube video using buttons. For instance, if the video is of a car race, there would be buttons labeled Lap 1, Lap 2, and so forth. My idea involves adding an extension to the vi ...

Obtain the leaf nodes from a combination of arrays and objects using Lodash

Here is the code structure I want to share with you before explaining my requirements. It displays the input array layout along with the desired outcome: [ { link: "someurl", name: "Foo", subCats: [ { link: "anotherurl", ...

Looking for a Search Field that clears default text when focused - Compatible with Firefox 3.6?

I have attempted various jQuery and JavaScript solutions found on this page: How to clear text field on focus of text field Surprisingly, all of the solutions work except for FF 3.6. So, I am wondering, What alternative can I use to make this feature com ...

How can Angular be used to create core styles in a CSS file rather than adding them dynamically within style tags?

Whenever I import a component, like MatTabsModule, it automatically generates styles within the head section: <style>.mdc-tab{min-width:90px;padding-right:24px....</style> I'd prefer to have all these styles generated in an external CSS f ...

Tips for preserving changes made to a jQuery script when the page is reloaded

Is there a way to retain jQuery script changes when the page is reloaded? I have a page where clicking on certain elements triggers events, and I want these changes to persist even after reloading the page, resetting only when the cache is cleared. I appre ...

Can you provide tips on how to center the title on the page?

Currently, I am working on codepen.io and have been tasked with creating a paragraph that includes a title. However, my dilemma lies in the fact that I need this title to be center-aligned without directly altering the "x" value. Unfortunately, CSS is not ...