Subscriber fails to receive updates from Behavior subject after calling .next(value)

I am facing an issue where a Behavior Subject does not update a subscriber upon the .next(value) call.

Being new to typescript, I believe I might be overlooking something small. The implementation seems correct based on what I have researched.

Although there were similar issues discussed on the site, none of the solutions provided were able to resolve my problem. An example of such a discussion can be found here

The RestService is only included in the app.module.ts providers array.

The Auth Guard File can be found in (services/auth-guard.service.ts)


authenticated = false;

...

    ngOnInit(){
        this.restService.isLoggedIn().subscribe({
            next: result => {
                this.authenticated = result;
            }
        });
    }

...

    canActivate(route: ActivatedRouteSnapshot): boolean{

        console.log(this.authenticated);

        if(!this.authenticated){
            this.router.navigate(['login']);
        }
        return this.authenticated;
    }
}

Sections of the rest service file (services/rest.service.ts)

import { HttpClient, HttpParams, HttpHeaders } from '@angular/common/http';
import { RequestOptions } from '@angular/http';
import { Injectable } from '@angular/core';
import { Storage } from  '@ionic/storage';
import { Observable, BehaviorSubject } from  'rxjs';
import { User } from  'src/app/Interfaces/user';
import { tap } from 'rxjs/operators';

...

authSubject  =  new  BehaviorSubject(false);

...

public _setAuthSubject(value){
    this.authSubject.next(value);
 }

public isLoggedIn() {
    return this.authSubject.asObservable();
  }

In the canActivate method, a console log always shows that this.authenticated is false. However, upon adding another subscriber call and checking the other variable, it becomes evident that it is actually true and has been updated. Am I overlooking something causing authentication not to be updated?

Additional information includes my app.module.ts:

@NgModule({
  declarations: [AppComponent],
  entryComponents: [],
  imports: [
    BrowserModule,
    IonicModule.forRoot(),
    AppRoutingModule,
    HttpClientModule,
    IonicStorageModule.forRoot()
  ],
  providers: [
    AuthGuardService,
    StatusBar,
    SplashScreen,
    { provide: RouteReuseStrategy, useClass: IonicRouteStrategy },
    SQLite,
    SQLitePorter,
    RestService,
  ],
  bootstrap: [AppComponent]
})

Also, the routing that invokes the auth guard service (app-routing.module.ts)

import { NgModule } from '@angular/core';
import { PreloadAllModules, RouterModule, Routes } from '@angular/router';
import { AuthGuardService } from './services/auth-guard.service';

const routes: Routes = [
  { path: '', loadChildren: './tabs/tabs.module#TabsPageModule', canActivate: [AuthGuardService]},
  { path: 'login', loadChildren: './login/login.module#LoginPageModule' },
];
@NgModule({
  imports: [
    RouterModule.forRoot(routes, { preloadingStrategy: PreloadAllModules })
  ],
  exports: [RouterModule]
})
export class AppRoutingModule { }

Lastly, here is the function that sets the auth subject to true (login/login.page.ts)

constructor(
    public menu: MenuController,
    private restService: RestService,
    private router: Router,
    private storage: Storage
  ) { }


  async login(form){

    this.restService.login(form.value).subscribe({
      next: response => {
        console.log(response)
        if(response.access_token){
          this.storage.set("ACCESS_TOKEN", response.access_token);
          this.restService._setToken(response.access_token);
          this.restService._setAuthSubject(true);
        }
        this.router.navigateByUrl('');
      },
      error: err => {
        console.log('ERROR!: ', err)
      }
    });
  }

Answer №1

I made some changes to AuthGuard by incorporating the following code. I learned that services shouldn't have code in ngOnInit, which was a beginner's mistake on my part. A big thank you to @ingkevin and @lchraf for their assistance.

    init(){
        this.restService.isLoggedIn().subscribe({
            next: result => {
                this.authenticated = result;
            }
        });
    }

    constructor(private router: Router, 
                public restService: RestService) {
                    this.init()
                }

ngOnInit has been eliminated.

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

Tips and tricks for setting up a functional react select component using Material UI

Having an issue with React Select material UI where the dropdown select is not functioning properly. The popup does not open up as expected. I am looking to display react select in a modal dialog box. import MenuItem from "@mui/material/MenuItem" ...

There was an error encountered while creating a new CLI using oclif: Subsequent variable declarations must be of the same type

I've been working on developing a new CLI tool using the oclif framework and TypeScript, but I'm encountering some issues when attempting to build the project. When I generate the CLI, it results in errors. Even when I try to manually run npm bu ...

Creating a TypeScript generic record with specified keys

I need to validate in TypeScript whether an object contains the specified keys (from SingleShopColumns or MultishopColumns) and has a validations property that is an array of strings. I am using Record and generics, but any simple method of representing t ...

Messages are not being emitted from the socket

I've been encountering an issue with message transmission from client to server while using React and ExpressJS. When I trigger the sendMessage function on the client side, my intention is to send a message to the server. However, for some reason, the ...

Is it possible to declare language features in Typescript? For example, changing `!variable` to `no variable`

Can Typescript language features be declared within the app's source code? I want to enhance code clarity by implementing a small feature. Modified Null Test if (no userDetails) { // handle null } This new null test syntax is a little more conc ...

Error: TypeScript compilation failed due to absence of tsc command in the system

Hello, I recently installed TypeScript and encountered an issue when trying to initialize tsc -v in the terminal. The error message I received was "bash: tsc: command not found." During the installation process, I used npm install -g typescript@latest whi ...

What is the best way to close ngx-simple-modal in angular7 when clicking outside of the modal component?

Can anyone help me with closing the modal in my angular7 app when the user clicks outside of the modal component? I have been using the ngx-simple-modal plugin, and I tried implementing the following code: this.SimpleModalService.addModal(LinkPopupCompone ...

Angular2+ test case indicating lack of NgControl provider

I've been facing an issue while testing an angular component with multiple dependencies. The test case fails with the error: "No Provider for NgControl". Here's the detailed error message: Chrome 66.0.3359 (Mac OS X 10.13.4) configurator compone ...

Creating a String Array and linking it to an Input Field

I'm currently working on a code that involves mapping through an array of strings using observables. My objective is to display the value from this array inside an input field. However, despite being able to view the array in the console, I encountere ...

Issue with Angular Checkbox: Inconsistencies in reflection of changes

I'm encountering a challenge with my Angular application where I have implemented multiple checkboxes within an options form. The issue arises when changes made to the checkboxes are not consistently displayed as expected. Below is the pertinent code ...

Fetching data in VueJs before redirecting to a new page

Within the mounted function, I am creating an action that fetches data from a Rest API and populates my table in a Vue.js component mounted() { UserService.getProjects().then( (response) => { this.isProject = true; this.project ...

Error in redirection while deploying Auth.js (v5) within a Docker container in a Next.js application

Has anyone successfully integrated the latest version of Auth.js into a production environment with Docker? I am currently utilizing the t3-stack (tRPC, Auth.JS, Prisma, Next.JS). I attempted to upgrade to the beta version with the Prisma Adapter, but enc ...

Retain annotations for assigned types in d.ts files

When compiling declarations for the code snippet below using Typescript v5.0.4, I encounter an issue: type SomeType<T> = { field: T; }; const getInstance = <T>( value: T ): SomeType<{ [K in keyof T]: T[K]; }> => { return { ...

Managing multiple HTTP requests in Ionic

I am having an issue with my http requests where I only receive the data from the first request and not all of them. Can anyone help me with this problem? Thank you in advance for your assistance. Here is my function: async asyncCall() { return awai ...

How to implement and utilize a history-object interface in React with Typescript?

Can you help me with setting up an interface for a history object in my component? Currently, it is typed as any and I want to type it appropriately. Object: https://i.sstatic.net/Sru8R.png Here's the code snippet: import React, { useState } from &a ...

Prevent users from clicking buttons until all mandatory fields are filled out using react-hook-form

I am seeking guidance on how to dynamically disable a button based on the input values of both Name and State in the given code snippet. Specifically, I want to restrict button functionality until both name and state fields are filled out, regardless of ...

What is the function of the Angular dependency injection mechanism?

I'm trying to grasp the inner workings of Angular/NestJs dependency injection. It's intriguing how the type of parameters gets lost when a Typescript class is constructed. For example: type Dependency1 = {}; type Dependency2 = {}; class X { ...

What is the best way to utilize a reduce function to eliminate the need for looping through an object in JavaScript?

Currently, my code looks like this: const weekdays = eachDay.map((day) => format(day, 'EEE')); let ret = { Su: '', Mo: '', Tu: '', We: '', Th: '', Fr: '', Sa: '' }; w ...

Utilizing next/image as a backgroundImage in a div container

Currently, I am working with nextjs and I am trying to set a background Image for a specific div using next/image. Most of the sources I found only explain how to implement full screen background images with next/image, not for a single div. I stumbled upo ...

Tips for extracting a keyword or parameters from a URL

I'm in the process of creating my personal website and I am interested in extracting keywords or parameters from the URL. As an illustration, if I were to search for "Nike" on my website, the URL would transform into http://localhost:3000/searched/Nik ...