Even after making changes within my Angular and Firebase subscription, my variable remains unchanged

In an attempt to secure my Angular application's routes, I decided to create a canActivate method that would check the user's status. My backend is based on Firebase, and user authentication, login, and sign up functionalities are all handled through Firebase. Here is the code snippet that I came up with:

constructor (private router: Router, private auth: AngularFireAuth) { 
    this.y = false;
    this.auth.authState.subscribe(x => {
      
      if(x == null){
        console.log("null if condition") // for tracking program flow
        this.y =  false;
        
      }
      else{
        console.log("else condition") // for tracking program flow
        this.y= true;
        
      }
      
      console.log("inside fun",this.y); // for tracking program flow
    })

  }

  canActivate(route:any, state: RouterStateSnapshot) {

    console.log("canActivate", this.y); // for tracking program flow
    if (this.y)
    { return true}
    else
    {
      this.router.navigate(['/login'], {queryParams: {returnUrl: state.url}});
      return false;

    }
    
  }

I need some assistance in understanding a situation where even though the y value changes within the subscription block when the user is logged in, it reverts back to its initialized value once outside of it. Any help would be greatly appreciated.

Answer №1

When working with Firebase/Angular, I believe there's a more efficient way to handle things. Check out the AngularFire Github repository for a one-line solution:

{ path: 'items', component: ItemListComponent, ...canActivate(redirectUnauthorizedToLogin) },

This simple line of code will redirect unauthorized users to a specified route, but you can also explore advanced options using the authguards provided in the package.

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

Instructions on how to sign up for a worldwide technique that is known as

I have a file called globalvars.ts where I added a global method. How can I subscribe to this method in the ts page where it is being called? globalvars.ts; httpgetmethod(url:string) { var veri; var headers = new Headers(); headers.append(' ...

Tips for effectively passing navigation as props in React Navigation with Expo

How can I correctly pass navigation as props to another component according to the documentation? The navigation prop is automatically provided to each screen component in your app. Additionally, To type check our screens, we need to annotate the naviga ...

Setting the default value for a dropdown in Angular 2 using Kendo UI

I'm currently facing an issue with creating a dropdownlist using Kendo UI. The problem arises when I try to set a default selected value upon loading the screen. Referring to their documentation, my code is structured like this: HTML: <kendo-drop ...

What could be causing Angular's Renderer2 to generate inaccurate outcomes?

Having an array of queries with varying positions of underscores: Newtons __________ Law dictates __________ is the result of an object's mass and speed. My goal is to show each question to users, replacing the blanks with in ...

Steps for passing an interface as a parameter in Angular services when making an HTTP GET request

Struggling with passing the interface as a parameter for performing an HTTP get request example.service.ts export interface Product{ Id:any; product : any; } public getProduct(item:Product): Observable<any> { const base = this.http. ...

How can we initiate an AJAX request in React when a button is clicked?

I'm fairly new to React and I'm experimenting with making an AJAX call triggered by a specific button click. This is how I am currently using the XMLHttpRequest method: getAssessment() { const data = this.data //some request data here co ...

Running my Angular Single Page Application on a self-hosted ServiceStack service

Currently, I am utilizing ServiceStack to construct a small self-hosted RESTApi service with a NoSQL database and the setup is working perfectly fine (without using .Net Core). My next step involves creating some maintenance screens using Angular. Howeve ...

Using TypeScript to assert the type of a single member in a union of tuples, while letting TypeScript infer the types of the other members

Currently, I am attempting to implement type assertion for the "error-first" pattern. Within my function, it returns tuples in the format of ['error', null] or [null, 'non-error']. The specific condition I want to check for is error = ...

Ag-Grid filter not displaying

In my HTML file, I have the following code: <ag-grid-angular #agGrid style="height: 300px" [rowData]="rowData" [columnDefs]="columnDefs" [gridOptions]="gridOptions" ...

Having trouble retrieving JSON file in Next.js from Nest.js app on the local server

Having just started with Next.js and Nest.js, I'm struggling to identify the issue at hand. In my backend nest.js app, I have a JSON API running on http://localhost:3081/v1/transactions. When I attempt a GET request through postman, everything functi ...

encountering difficulties calling setAttribute within a function

I am encountering an issue while attempting to use setAttribute() within toggleDiv(). My IDE does not seem to recognize the function and is throwing an error. How can I resolve this problem so that the function is recognized? This specific case relates t ...

Issue with Angular 7: In a ReactiveForm, mat-select does not allow setting a default option without using ngModel

I have a Angular 7 app where I am implementing some reactive forms. The initialization of my reactive form looks like this: private initFormConfig() { return this.formBuilder.group({ modeTransfert: [''], modeChiffrement: [' ...

When using Jest + Enzyme to test a stateful class component, encountering problems with Material-UI's withStyles functionality is a common issue

I have a React + TypeScript application with server-side rendering (SSR). I am using Material-UI and following the SSR instructions provided here. Most of my components are stateful, and I test them using Jest + Enzyme. Below is an example of one such com ...

Error: The argument provided cannot be assigned to a parameter that requires a string type, as it is currently a number

Currently, I am in the process of migrating some older websites to TypeScript. However, I keep encountering a type error during the build process. The specific error message is Type error: Argument of type 'number' is not assignable to parameter ...

I need help combining my node project with Angular - how do I do it?

After creating a project in nodeJs to update my database, I also developed a separate project in Angular for the front end design of a form. Now, I am looking to combine these two projects so that the form data submitted in the Angular project can be proc ...

Encountering issues with Typescript when providing parameters for res.status().json()

I've recently started using Typescript and I'm still in the learning process by converting some existing JS code to TS. In my code: res.status(200).json({ user: data.user }) I encountered a red squiggly underline under user:data.user ...

Personalized information box utilizing Reactive Extensions in JavaScript

I am currently working on implementing a custom tooltip for a diagram using the vis-network library and RXJS. The key concept is to have: An observable named diagramElementHover$ to display the tooltip An observable named hideTooltipObs$ to hide the too ...

Secure Your Passwords with Encryption in NestJS using @nestjs/mongoose before saving them

Seeking to encrypt passwords before saving using @nestjs/mongoose. Came across examples written in pseudocode like this: UsersSchema.pre('save', (next: any) => { if (!this.isModified('password')) return next(); this.password = en ...

The issue arises when attempting to update the input of a child component within a reactive form during the OnInit lifecycle

My dilemma arises in working with data stored in the ngrx entity store, as it gets displayed in chunks based on pagination. The issue lies with rxjs somehow remembering the paging history. For instance, when I fetch the first page of data from the server, ...

Guide on including a in-browser utility module from single-spa into a TypeScript parcel project

There are 3 TypeScript projects listed below: root-config a parcel project named my-app an in-browser utility module called api All of these projects were created using the create-single-spa command. In the file api/src/lomse-api.ts, I am exporting the ...