Angular2: Ensuring Sequential Execution Line by Line - A Comprehensive Guide

I have a designed an Angular2 Navbar Component that features a logout button:

import { Component, OnInit } from '@angular/core';
import { LoginService } from '../login.service';
import { Router } from '@angular/router';

@Component({
  selector: 'app-navbar',
  templateUrl: './navbar.component.html',
  styleUrls: ['./navbar.component.css']
})
export class NavbarComponent implements OnInit {

    loggedIn: boolean;

    constructor(private loginService: LoginService, private router : Router) {
        if(localStorage.getItem('PortalAdminHasLoggedIn') == '') {
            this.loggedIn = false;
        } else {
            this.loggedIn = true;
        }
    }

    logout(){
        this.loginService.logout().subscribe(
            res => {
                localStorage.setItem('PortalAdminHasLoggedIn', '');
            },
            err => console.log(err)
            );

        this.router.navigate(['/login']);
        location.reload();
    }

    getDisplay() {
    if(!this.loggedIn){
      return "none";
    } else {
      return "";
    }
  }

  ngOnInit() {
  }

}

When the logout button is clicked, what I anticipate is for the logout() function in the LoginService to be executed first, then update the localStorage variable, navigate to the login component, and finally reload the page.

However, there are instances where the page reloads before the logout() function in the LoginService is executed, which results in the localStorage not being updated. How can I modify the code to ensure it executes in the correct order?

Any suggestions or advice would be greatly appreciated. Thank you!

Answer №1

Whenever you initiate an asynchronous task, like logging out, the code will not follow a sequential order. The argument passed to the .subscribe method is essentially a callback function that will be triggered at an undetermined later time. To ensure that certain code runs only after this process is complete, it must be invoked from inside the subscribe method.

logout(){
    this.loginService.logout().subscribe(
        res => {
            localStorage.setItem('PortalAdminHasLoggedIn', '');
            this.router.navigate(['/login']);
            location.reload();  // <-- what is this for?
        },
        err => console.log(err)
        );
}

I am curious about the purpose of the location.reload(). Is it necessary to reload the page after navigating?

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

When using TypeScript's array intersection type, properties are not accessible when using methods like Array.forEach or Array.some. However, they can be accessed within a for loop

It was challenging to search for this problem because I may not have the correct technical terms, but I hope my example can help clarify it. Background: I am using query data selectors in react-query to preprocess query results and add some properties tha ...

Angular application has the capability to dynamically load plugins without the need for recomp

As I work on developing the frontend of my Web Api (NET CORE) pluginable application, my goal is to utilize Angular 9. However, I must admit that I am not well-versed in this framework. In terms of my backend, it was crafted with extensibility in mind. At ...

"Utilizing Postgresql with TypeORM for filtering many-to-many relationships

I have two entities that are connected with a ManyToMany relationship: // Branch entity @ManyToMany( (type) => User, (e) => e.branches ) users: User[]; // User entity @ManyToMany( (type) => Branch, (e) ...

What is the best way to utilize scope apply or run functions upon successful completion in Angular 8 jQuery ajax requests?

Due to reasons that I won't delve into here, I have opted to use jQuery ajax instead of Angular's http. This means I am making an ajax call to my php server. However, a problem arises where any code within the success/error blocks is confined to ...

Angular developers may encounter a dependency conflict while attempting to install ngx-cookie

I'm currently facing an issue while attempting to add the ngx-cookie package for utilizing the CookieService in my application. Unfortunately, I am encountering some dependency conflicts that look like the following: $ npm install ngx-cookie --save np ...

What is the process of transforming an object type into a two-dimensional array using lodash?

In order to properly display multiple tables in my Angular project, I am looking to convert an object type into an array of different objects. The object I am working with is as follows: let myObject = { internalValue:{city:"Paris", country:"France", pin ...

Is it possible to use a Jasmine spy on a fresh instance?

In need of assistance with testing a TypeScript method (eventually testing the actual JavaScript) that I'm having trouble with. The method is quite straightforward: private static myMethod(foo: IFoo): void { let anInterestingThing = new Interesti ...

What is the best way to convert one array of types to another array of types in Typescript?

Imagine you have the following: type AwesomeTuple = [string, number, boolean] Now, you're looking to transform that type using a generic approach: type AmazingGeneric<T extends any[]> = ... In this scenario: AmazingGeneric<AwesomeType> w ...

"Utilizing aws-sdk in a TSX file within a React project: a step-by

When working on a project using TypeScript (tsx) for React, I encountered an issue with uploading images to the server using aws-sdk to communicate with Amazon S3. To resolve this, I made sure to install aws-sdk via npm and typings. UploadFile.tsx import ...

Encountered error when attempting to clone Angular project using npm: ELIFECY

Hi there, I'm facing an issue with cloning my Angular project. Whenever I try to run the frontend using IntelliJ or VSCode, I'm encountering this error message: C:\Users\developer.me\Downloads\TestClone\node_modules&bsol ...

npm encountered an issue when attempting to install a package from a local directory: EISDIR: illegal operation on a directory, read

While attempting to add my compiled TypeScript output as a local package using npm, this error appears: $ npm install --save ../app/out npm ERR! eisdir EISDIR: illegal operation on a directory, read npm ERR! eisdir This is most likely not a problem wit ...

Error encountered during password reset in Auth0

I am currently working with Angular 2 and using lock version 10.8 in an attempt to implement a feature that allows users to change their password. I've been experimenting with the following method, which involves calling the Management API. In this me ...

What is the best way to make my if statement pause until a GET request finishes (GUARD) with the help of Angular?

I am currently working on implementing admin routes for my Angular app, and I have used a role guard to handle this. The code snippet below showcases my implementation: However, I would like the get request to finish executing before the if statement begi ...

Stop the current HTTP request and initiate a new one asynchronously

My custom component showcases a detailed view of a selected building along with a list of its units (apartments). Below is the HTML code for this component: <div *ngIf="$building | async as building"> ... <div *ngIf="$buildingUnit ...

Discover the most helpful keyboard shortcuts for Next.js 13!

If you're working with a standard Next.js 13 app that doesn't have the experimental app directory, setting up keyboard shortcuts can be done like this: import { useCallback, useEffect } from 'react'; export default function App() { c ...

Attempting to render the application results in an error message stating: "Actions must be plain objects. Custom middleware should be used for asynchronous actions."

I am experiencing an issue while testing my vite + typescript + redux application to render the App component using vitest for testing. I am utilizing redux@toolkit and encountering a problem when trying to implement async thunk in the app component: Error ...

Bidirectional enumeration in TypeScript

I am working with an enum defined as: enum MyEnum { key1 = 'val1' key2 = 'val2' } However, I am unsure how to create a SomeType implementation that fulfills the following requirements: Function: const myFunction = (param: SomeT ...

Sharing an array of React objects with PHP using REACT JS

I am new to React JS and I have a question regarding sending files as a react object array to php $_FILES using axios. Any help is appreciated, thank you in advance. Here is my react code: This is the code snippet: <Row> <Col lg={4}> ...

Who is in charge of initializing "background" services within Angular?

I have been studying the Angular service workers documentation (https://angular.io/guide/service-worker-communications). The examples provided demonstrate services used for managing service worker lifecycle handlers such as update and failed lifecycle. My ...

Is there a way to trigger the opening of the mat-autocomplete panel when an option is selected in a different mat-autocomplete component?

Is it possible to trigger the opening of a mat-autocomplete panel when an option is selected in another mat-autocomplete? To see an example, please check out this demo. ...