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

Adjust the size of an Angular component or directive based on the variable being passed in

I'm looking to customize the size of my spinner when loading data. Is it possible to have predefined sizes for the spinner? For example: <spinner small> would create a 50px x 50px spinner <spinner large> would create a 300px x 300p ...

What is the solution to the error message Duplicate identifier 'by'?

While conducting a test with the DomSanitizer class, I made some changes and then reverted them using git checkout -- .. However, upon doing so, I encountered a console error: Even after switching to a different git branch, the error persisted. Here are ...

I encountered an error with Firebase when attempting to run functions on my local machine

Encountering a Firebase error when running the function locally using emulator in CLI $ firebase emulators:start --only functions Initiating emulators: ["functions"] functions: Using node@8 from host. functions: Emulator started at http://localhost:50 ...

Is there a way to implement retry functionality with a delay in RxJs without resorting to the outdated retryWhen method?

I'd like to implement a retry mechanism for an observable chain with a delay of 2 seconds. While researching, I found some solutions using retryWhen. However, it appears that retryWhen is deprecated and I prefer not to use it. The retry with delay s ...

Having trouble executing the project using Gulp

I'm a beginner in front-end development and I am working on an existing project that I'm having trouble running. According to the documentation, I should run the project by executing: $ gulp && gulp serve But I keep getting this error: ...

Converting language into class components using ngx-translate in Angular

Seeking to convert the information from a table into my typescript class. The data in the table is sourced from a JSON file within the /assets directory. Is there a method to accomplish this task? How can I categorize translation within a typescript class ...

What is the functionality of ngModel in the Angular Heroes Tour tutorial?

Hello everyone, this is my first post here. I have been diving into the Angular Tour of Heroes using Angular 6 and I think I understand how ngModel works, but there's one thing that puzzles me. How does it manage to update the data in my list when th ...

Issue with React not displaying JSX when onClick Button is triggered

I've recently started learning React and I'm facing a problem that I can't seem to figure out. I have a basic button, and when it's clicked, I want to add another text or HTML element. While the console log statement is working fine, th ...

When an action is clicked within a cell of an Angular Material table row, the (click) event for that row is triggered

Is there a way to activate a modal using a button within a mat-table without triggering the row click event? I've come across Angular Material 2 Table Mat Row Click event also called with button click in Mat Cell but implementing $event.stopPropagatio ...

Encountering an issue with MUI Props: "Must provide 4 to 5 type arguments."

I'm attempting to use a custom component and pass in AutocompleteProps as a prop, all while utilizing typescript. Here's my current setup: type Props = { autoCompleteProps?: AutocompleteProps<T> label: string loading?: boolean } cons ...

Tips for customizing the appearance of a mat-select chosen item?

Is there a way to modify the color of the selected option text in a mat-select component within an Angular 15 project? .html <mat-form-field> <mat-label>From</mat-label> <mat-select panelClass="mat-select-red"> ...

Retrieving information from a JSON file utilizing an Interface

For the purpose of learning, I am developing a small Ionic app where I want to load data from a JSON file and map it to an interface that defines the data structure. However, I am facing challenges in achieving this: import { Component } from "@angular/co ...

Exploring the wonders of delayed execution through rxjs

I am looking for a way to incorporate delayed execution into my application. Specifically, I want to prevent server requests from being sent while the user is still typing in a search string. This functionality is commonly seen in search engines like Goo ...

"Introducing the new Next.Js 14 sidebar featuring a sleek hamburger menu

I am in the process of developing a chat application. Currently, I have a sidebar that displays existing conversations and I would like to make it responsive by implementing open and close functionalities for mobile devices. Here is the code snippet for m ...

Tips for setting variable values in Angular 7

I'm encountering an issue with assigning values to variables in my code. Can anyone provide assistance in finding a solution? Here is the snippet of my code: app.component.ts: public power:any; public ice:any; public cake:any; changeValue(prop, ...

Executes the function in the child component only if the specified condition evaluates to true

When a specific variable is true, I need to call a function in a child component. If the variable is false, nothing should happen. allowDeleteItem = false; <ChildComponent .... removeItemFn={ deleteFn } /> I attempted to use the boolean variable wi ...

Using Angular 5 to integrate a jQuery plugin

Recently, I've started learning Angular and am currently using version 5. I need to integrate a plugin called 'jquery-circle-progress' into my project. The plugin can be found at this link: I managed to install the plugin using npm and adde ...

What are some strategies for managing multiple versions of NPM and Node? Is there a way to install Angular for a single project without affecting other projects?

I have been tasked with working on two separate projects that rely on NPM and Node. The first project was developed using Ionic, while the new one requires Angular exclusively. Initially, only the Ionic project was set up on my laptop, so all installations ...

Leveraging an intersection type that encompasses a portion of the union

Question: I am currently facing an issue with my function prop that accepts a parameter of type TypeA | TypeB. The problem arises when I try to pass in a function that takes a parameter of type Type C & Type D, where the intersection should include al ...

What is the reason behind the mandatory credentials option for the CredentialsProvider?

When using NextAuth.js with a custom sign in page, some code examples for the credentials provider do not include the credentials option in the CredentialsProvider. According to the documentation (here), the credentials option is meant to automatically "ge ...