The "next" method of the Angular BehaviorSubject is malfunctioning

I previously wrote a code in Angular 4 that was functioning flawlessly, however, after migrating to Angular 6, a part of it seems to be broken. I would greatly appreciate any assistance with this issue.

One problematic area is within the AuthService class:

export class AuthService {

    private loggedIn = new BehaviorSubject<boolean>(false);

    isUserLoggedIn(): Observable<boolean> {
        return this.loggedIn.asObservable();
    }

    login(username: string, password: string) {
        let body =
        {
            username: username,
            password: password
        };

        return this._http.post(Settings.apiEndpoint + "users/authenticate", body)
            .map(res => {
                localStorage.setItem('token', res["token"]);
                localStorage.setItem('username', res["username"]);
                this.isLoggedIn = true;
                this.loggedIn.next(true);
                return res;
            })
            .catch(error => {
                this.clearAuthData();
                return Observable.throw(error)
            });
    }

    logout() {
        localStorage.clear();
        this.isLoggedIn = false;
        this.loggedIn.next(this.isLoggedIn);
    }
}

The code snippet above showcases how I subscribe to the subject in my AppComponent's ngOnInit:

this._auth.isUserLoggedIn()
            .subscribe(
                d => {
                    console.log("d here", d);
                    if (d)
                    {
                        this.isLoggedIn = true;
                        this.username = this._auth.getUsername();
                    }
                    else {
                        this.isLoggedIn = false;
                    }
                },
                d => {
                    console.log("error.");
                },
                () => {
                  console.log("bull.");
                }
            );

The main problem arises when logging out - the AppComponent appropriately reacts to the observable. However, upon logging back in, there seems to be an issue where the component fails to acknowledge the change. Despite maintaining the code as it was during the Angular 4 implementation, I am unable to discern why the login event is not being triggered.

Answer №1

The issue with your code is due to a breaking change in rxjs 6, where version 5.5 introduced pipeable operators.

Previously:

source.map(x => x * 2).catch(() => of('ups'))

Now:

source.pipe(map(x => x * 2), catchError(() => of('ups')))

Additionally, they have made some changes such as moving catch() to catchError(), do() to tap(), switch() to switchAll(), and finally() to finalize()

[Edit] Remember to import your rxjs operators like this: import { map } from 'rxjs/operators';

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

bento-ng-d3 is missing from the npm registry, along with other bento packages, including Angular

I have encountered a dependency in my Angular project's package.json file that includes the following: "@bento/bento-ng":"8.4.1", "@bento/bento-ng-d3":8.4.1, "@bento/bento-ng-datamap":8.4.1, "@bento/bento-n ...

Child stateless component in React receiving outdated props from parent Class component

Within my Parent Component, there is a form that users interact with. The form displays real-time information that updates as fields are edited. However, I am encountering an issue where the child component sometimes receives outdated props from the previo ...

Setting a cookie within an Angular interceptor

My angular interceptor function includes a request object. intercept(req: HttpRequest<any>, next: HttpHandler) { return next.handle(req); } I am looking to set my token in the request cookie under the name my-token. How can I achieve this? I ...

Putting Tailwind pruning to the test in a React application using Jest

Is there a way to test Tailwind's pruning using Jest without the need for custom postcss configuration? Can it be done by solely implementing the default webpack config created by CRA 5 (as explained here)? It appears that Tailwind is not applying st ...

Incorporating Moment.js into React Native Typescript for Enhanced Date and

I am currently facing an issue while using Moment.js and React Native to work with date and time. My code snippet below showcases how I am attempting to utilize the library. import * as React from 'react'; import { Text, View, StyleSheet } from ...

Achieving text alignment with icons in Angular

I'm having trouble aligning my text with the icon next to it despite trying to adjust margins. I would really appreciate any help or suggestions on how to resolve this issue. <div class="notification" [ngClass]="{'no ...

Library of Functions in Angular 2

As I develop my application, I'm considering creating a functions library that can be utilized by various components. What would be the most effective approach to achieve this? Should I create a service containing all the functions, or rely on classes ...

Using Express middleware in a TypeScript Express application

I'm currently converting the backend of an ExpressJS application to Typescript. While working on the auth.routes.ts file, I encountered an issue with the middleware (authMiddleware). It seems like there might be a typing error, as the same code in the ...

Unable to find module 'child_process'

Here is the content of my main.ts file: import { enableProdMode } from '@angular/core'; import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; import { environment } from './environments/environment'; if ...

Updating the countdown label in NativeScript and Angular

I am currently working on a timer countdown component and have the following code: @Component({ moduleId: module.id, selector: 'time-countdown', template: `<StackLayout> <Label text="{{timeRemaining}}" ></La ...

MockStore has not been configured as a provider

My current challenge involves testing my app.component using Cypress. This component is supposed to fetch data from the ngrx store, and I've made sure to refer to the official documentation for guidance on setting up the test. Here's how the test ...

Removing scrollbar from table in React using Material UI

I successfully created a basic table using react and material UI by following the instructions found at: https://material-ui.com/components/tables/#table. The table is functioning properly, but I am finding the scrollbar to be a bit inconvenient. https:// ...

What is the best way to loop through a template literal union type in JavaScript?

Is there a way to iterate over the different values in a string union type created with template literals? type Foo = "Foo" | "Foo2" | "Foo3"; type Bar = "Bar" | "Bar2" | `${Foo}Type`; One common approach is to use a <const> assertion, like this: c ...

Initiate a button press upon pressing the space bar

Currently, I am only able to use the click function on the button. However, I am also interested in incorporating the enter key and space bar for this action. Button (click)="ShuffleClick()" ...

Utilizing Third-Party JavaScript Libraries in Typescript

After researching different Q/A threads, I found a method for incorporating external libraries in TypeScript. Following the recommendations, I successfully registered BT alert to an element using the following code snippet: import * as $ from "jquery"; im ...

Creating horizontal cards with Angular MaterialWould you like to learn how to design

I need help converting these vertical cards into horizontal cards. Currently, I am utilizing the Angular Material Cards component. While I can successfully create cards in a vertical layout, my goal is to arrange them horizontally. Below is the code sni ...

Firebase functions are having trouble identifying the routes in the express app that are located outside of the

Recently, I faced an issue while deploying a TypeScript project to firebase-functions where all the code was stored in index.ts. Initially, everything worked fine but when I decided to refactor my code, I discovered that firebase was not able to recognize ...

Encountered an error: Response returned a status of 404 Not Found while trying to access

I am encountering a problem while trying to run an Angular and Node.js application that I am attempting to integrate with a Neo4j app. The issues manifest as the following errors: POST http://localhost:7474/viewNodesStart 404 (Not Found) and EXCEPTION: ...

Error in BehaviorSubject<any[]>: Unable to assign type 'any[] | null' to type 'any[]'

When I try to pass a BehaviorSubject from my CacheService to a component @Input() that expects an array, I encounter an error stating that 'any[] | Type 'any[] | null' is not assignable to type 'any[]'. This occurs even though the ...

Exploring Angular's Structural Directive for Parsing HTML Strings

I need help parsing an HTML string with a structural directive inside ng-template. Currently, it is being displayed as a string instead of the desired outcome where the structural directive iterates three times and shows three li elements. How can I achiev ...