Function that returns an Observable<Boolean> value is null following a catch block

Why is the login status null instead of false in this method?

// In the method below, I am trying to return only true or false.
isLoggedIn(): Observable<boolean> {
    return this
        .loadToken()
        .catch(e => {
            this.logger.info(e); // This message is logged...
            this.token = null;
            return Observable.of(false); // I explicitly return false here.
        })
        .map(_ => this.token && this.token.access_token.length > 0);

This method is called from here

return this.authService.isLoggedIn().map(_ => {
    this.logger.info(`authorisation guard :: login status ${_}`);
    if (_)
        return true;
    this.router.navigate(["login"]);
    return Observable.of(false);
}).catch(_ => {
    this.logger.info(`authorisation guard :: login error ${_}`);
    this.router.navigate(["login"]);
    return Observable.of(false);
});

The following message gets logged:

2017-09-09T06:55:46Z [INFO] authorisation guard :: login status null

I am expecting:

2017-09-09T06:55:46Z [INFO] authorisation guard :: login status false

Answer №1

If you place the catch before the map, it can lead to unintended consequences:

isLoggedIn(): Observable<boolean> {
return this
    .loadToken()
    .catch(e => {
        this.logger.info(e);
        this.token = null;
        return Observable.of(false);
    })
    .map(_ => this.token && this.token.access_token.length > 0);

Placing the catch before the map means that errors in loadToken will be caught by the catch and the observable chain will continue with Observable.of(false).

As a result, false will go to the map where it will be disregarded. The value of this.token (which is likely null) will then be returned, failing the initial test in the logical expression.

To avoid this issue, consider moving the catch after the map.

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

Reusing a lazy-loaded module across multiple applications

Currently, I am working on an enterprise Angular 2 application with numerous lazy loaded modules. A new project came up where I needed to reuse a module that was previously created for the main app. After researching online, the only solution I found was ...

Ways to access the value of an input field using Javascript

I am currently utilizing the valums-file-uploader plugin for file uploads via ajax. However, I have encountered an issue with its functionality. Below is the script that I am using: <input type="text" id="Gaurav" name="Gaurav" /> <script src="fil ...

By utilizing ngOnInit() over a constructor, the @Input() property remains uninitialized

If this design is considered terrible, I am more than willing to make changes. Within my index.html, in the body section, I have: <month [year]="2016" [monthOfYear]="4">Loading...</month> The contents of month.component.ts are as follows: i ...

Entering information into fluctuating object fields

Suppose I have a dynamic object with a union type: data: {[key in 'num' | 'str' | 'obj']: number | string | object}; I set the object properties as follows: data.num = 1; data.str = 'text'; data.obj = {}; E ...

Angular/Typescript code not functioning properly due to faulty expressions

What could be causing my {{ expression }} to malfunction? I have exhausted all options, yet the web browser fails to recognize this {{ expression }} or properly bind it using ng-bind. Instead, it either displays the {{ expression }} as is or not at all. C ...

Using TypeORM to Retrieve Data from Many-to-Many Relationships with Special Attributes

Hey there, I'm diving into the world of TypeORM and could really use some guidance. I've been attempting to set up many-to-many relationships with custom properties following the instructions provided here However, I've run into a few iss ...

Certain CSS styles for components are missing from the current build

After building my Vue/Nuxt app, I noticed that certain component styles are not being applied. In the DEVELOPMENT environment, the styles appear as expected. However, once deployed, they seem to disappear. All other component styles render properly. Dev ...

Trouble communicating between Angular HttpClient POST request and Spring Controller

I'm encountering difficulties while trying to perform a POST request from my Angular frontend service class to the backend Spring controller. Despite my efforts, I am unable to see the log.info message from the controller unless I manually trigger th ...

Exploring the world of JMeter: capturing sessions with JavaScript and jQuery

I need to capture a user session in order to conduct a performance test. I have been using the JMeter HTTP(S) Test Script Recorder, but unfortunately it is not recognizing javascript and jquery. The error message I'm receiving is: JQuery is not def ...

Using ngrx, only the Array inside the Object retrieved by the GET-response is required

My issue involves using ngrx and trying to receive an Array of type "ReceivingObject". However, the problem arises when the GET-response returns it as an Array inside an Object structure. { "receivingObject": [ { "type": "xxx", "value": ...

Modifying the CSS based on the SQL data retrieved

I'm currently diving into the world of php and jquery, attempting to build a webpage that displays player information and their status fetched from my Mysql server. Although the core code is functional, it's a mashup of snippets gathered from va ...

Adjust choices in a dropdown menu based on the selection of another dropdown menu

I am attempting to create a scenario where selecting an option from one dropdown list will dynamically change the options available in the next dropdown list. You can find my code on jsfiddle <!DOCTYPE html> <html> <body> &l ...

Guide to implementing real-time filtering for a table through user input in a text box

https://i.stack.imgur.com/6DTAb.jpgI have a task to complete for an assignment. The assignment requires implementing client-side filtering of data as text is entered in a text box. I need guidance on how to implement it. Below is the problem statement for ...

Struggling to bring in components in ReactJS

My journey with ReactJS has just begun, and I've encountered some issues with the code that I believe should work but doesn't. To start off, I set up a new ReactJS project using the npm command create-react-app. Following this, I installed Googl ...

Implementing meta tags in React.js

I am attempting to incorporate dynamic meta-tags on each page of my website. However, despite my efforts, I cannot seem to locate the meta-tags in the page's source code. Do I need to make adjustments in public/index.html, considering that I am not ut ...

Generating a random number to be input into the angular 2 form group index can be done by following these

One interesting feature of my form is the dynamic input field where users can easily add more fields by simply clicking on a button. These input fields are then linked to the template using ngFor, as shown below: *ngFor="let data of getTasks(myFormdata); ...

Strategies for efficiently managing multiple subscriptions in an Angular form using minimal code and best practices

I am currently working on an Angular form that includes multiple select options managed by Subscriptions. However, I find myself writing a lot of code for each Subscription and would like to improve this process. Could someone provide some best practices ...

What is the best way to switch the site header in JavaScript or jQuery?

I have created a Bootstrap menu design and I am looking to add a sliding functionality to it. My goal is to hide the menu when scrolling down and display it when scrolling up (slide-down / slide-up). For implementing this feature, I plan to utilize jQuery ...

What are the distinctions between using findById({_id:historyId}) and findById(historyId) in Mongoose?

While working on one of my projects, I encountered a situation that left me a bit confused. I am trying to understand if both approaches outlined below will yield the same output, and if so, why? async getHistory( historyId: string) { const { h ...

Activate tooltip by clicking outside of the dropdown menu

I am experiencing an issue with a tooltip and a dropdown menu. Whenever I interact with the dropdown by clicking outside of it or inside its contents, the tooltip content is triggered again. For example, when I hover over the button, the tooltip triggers ...