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

Guidelines for creating a routing for a child component using Angular

Seeking assistance with setting up routing in an Angular application. I have a main component called public.component, and the auth.component component is inserted from the child module Auth.module using the selector. How can I configure the routing for th ...

What is the best way to ensure that each service call to my controller is completed before proceeding to the next one within a loop in Angular?

Calling an Angular service can be done like this: this.webService.add(id) .subscribe(result => { // perform required actions }, error => { // handle errors }); // Service Definition add(id: number): Observable < any > { retu ...

Sentry platform is failing to record network-related problems

Incorporating Sentry into my Next.JS application has allowed me to easily detect JavaScript errors such as reference or syntax issues on the Sentry platform. Unfortunately, I have encountered some challenges as Sentry is not logging any network-related er ...

Guide on sending several HTTP requests from a Node.js server with a shared callback function

Is there a way to efficiently make multiple HTTP calls in a Node.js server with a shared callback function? Are there any modules or libraries that can help with this? ...

The Instagram Basic Display API encounters an issue when processing a request for a user profile that does

Following the migration of our code from legacy api to basic display, we encountered an issue where no media is being retrieved for users who have not set their age in their profile. Instead, we are consistently receiving the following error: { "err ...

Disregard the sorting of rows in the MUI Datagrid

Any advice on excluding the "TOTAL" row from sorting in MUI library? onSortModelChange={(test, neww) => { neww.api.state.sorting.sortedRows = [14881337, 2, 3] neww.api.setState({...neww.api.state}) } } Review ...

Tips for extracting only the filename from chokidar instead of the entire file path

I am trying to capture the filename that has been changed, removed, or renamed, but I am currently receiving the full file path. Question: How can I extract only the filename when it is changed, instead of working with the entire file path? This is what ...

In CodeIgniter, the $this->input->post() function consistently returns an empty value

I'm encountering an issue where the value from an AJAX post always turns out empty. Even after confirming that the value is correct before the post, I'm unable to retrieve it using $this->input->post() HTML <?php if ($product_info->stock ...

Avoid causing the newline character to display

var i = 'Hello \n World' console.log(i) /* Output: Hello World */ /* Desired output: Hello \n world */ var j = 'javscr\u0012ipt' console.log(j) /* Output: javscr ipt */ /* Desired output: javscr\u0012ipt */ ...

Angular.js - organizing a list of items and preserving the outcome

Here is a compilation of randomly arranged items: <ul class="one" drag-drop="page.items"> <li ng-repeat='item in page.items|orderBy:page.random as result'> <img ng-src="http://placecage.com/{{item.id*100}}/{{item.id*100}}"& ...

Creating numerous pre-signed URLs using an Application Programming Interface

An API has been developed to generate pre-signed URLs for files stored in a private S3 bucket. The goal is to store these URLs in an array for access from another application. ["FILE1 pre-signed URL", "FILE2 pre-signed URL", etc..] However, there seems to ...

Send form data without reloading the page and connect it to a JavaScript script

I've designed a system that reveals values based on a specific input selection. Below is the main form where users can enter model numbers and press enter: <form> <input type="text" name="ModNum" id="ModelNumber" pattern="^PIV13RT[23]?$" ...

Looking for a way to notify users about page expiry with an Angular 5 service?

I have multiple pages each containing numerous forms. I am looking to develop a monitoring service for these forms. These forms are connected to data model objects with a high number of properties. I attempted to use the watchjs library to track changes in ...

How to Deactivate the Default Selection in React-Select

Having trouble with the focus in a React Select dropdown. The first item always gets focused when opening the dropdown, despite passing various props without success. I checked their GitHub for related issues around autofocus but couldn't find a solut ...

Having trouble initiating the server using npm start

Just starting out with nodeJs: I have created a server.js file and installed nodejs. However, when I try to run "npm start", I encounter the following errors. C:\Users\server\server.js:43 if (!(req.headers &amp;& req.headers. ...

What is the best way to add a value to a nested JSON array in Angular 5?

Need help transferring nested JSON data format from Web API to Angular5 {"contractId":1, "contractName":"Temp", "contractServiceList":[ {"id":1, "serviceId":{"serviceId":1,"serviceName":"Emergency Room"}, "providerTier":"Tier 1", "coi ...

The most effective method for acquiring an object through inheritance

I'm seeking advice on the best practice for adding behavior to an object received as a JSON object. I have REST services that allow me to define a sort of state machine. The API defines a /sessions resources. When creating a session via POST /sessio ...

Adjusting the width of row items in Angular by modifying the CSS styles

I am envisioning a horizontal bar with items that are all the same width and evenly spaced apart. They can expand vertically as needed. Check out the updated version here on StackBlitz Issue: I am struggling to automatically set the width of the row elem ...

Automatically assign the creation date and modification date to an entity in jhipster

I am currently working on automatically setting the creation date and date of the last change for an entity in JHipster, utilizing a MySQL Database. Below is my Java code snippet for the entity: @GeneratedValue(strategy = GenerationType.AUTO) @Column(nam ...

Extending the type of parameters in TypeScript

I am trying to call a function from my UI library with a parameter type that extends the original (Suggestion) type by adding more properties. I found a resource that suggests it is possible here: https://github.com/Microsoft/TypeScript/issues/2225 (in the ...