angular 2 loading elements synchronously

Within my local or session storage, there exists a JWT token containing the userId information.

When a user refreshes the page on a route such as

test.com/route2

the app.components.ts initiates an http request to fetch the roles.

    constructor(
    private userService: UserService
   )
  {
    this.userService.getUser(this.subId()).toPromise().then((data)=>{      this.setLoggedUser(data);
});
  }

The issue arises in the ngInit event of Route2, which is handled by route2.component.ts. I am sending an http request to retrieve customer data, but it gets executed before the LoggedUser is set, resulting in a null error.

   this.groupService.getAllCustomersOfGroup(this.getLoggedUser().Group.Id).subscribe(
  data => this.customers = data,
  err => this.error(err),
  () => { this.loadingHideSucces(); }
);

Answer №1

To ensure proper data fetching order, it is important to chain your calls correctly. For example, you can create a method called retrieveCurrentUser() that returns an Observable:

ngOnInit() {
  this.retrieveCurrentUser().switchMap(user=>{
    this.groupService.getAllCustomersOfGroup(user.Group.Id).subscribe(
        data => this.customers = data,
        err => this.handleError(err),
        () => {
            this.hideLoadingSuccess();
        }
    );
  })
}

retrieveCurrentUser():Observable<CurrentUser>{
 // logic to fetch user data and return as an observable.
}

If your component is labeled "route2," it may be used within an ng-router-outlet tag. In that case, consider utilizing a Resolve Guard.

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

Turn off page animation for a specific page in Ionic 4

While I know that disabling page transitions in the app.module.ts file using IonicModule.forRoot({animated: false}) will turn off transitions and animations for the entire app, I am looking for a way to only disable the page transition for a particular p ...

Guide to easily printing a page in Angular 4 using TypeScript

When using my web app, there are certain pages where I need to print only a specific component without including the sidebar. I have written the following TypeScript code to achieve this: print() { window.print(); } The relevant HTML code begins with: & ...

Tips on dynamically passing values according to media queries

Within my product section, there is a total of approximately 300 products. To implement pagination, I have utilized the ngx-pagination plugin. The products need to be displayed based on media query specifications. For example, if the viewport size falls wi ...

Having trouble assigning an initial value to ngx-bootstrap typeahead

Hello there, I am currently using Angular version 16 with ngx-bootstrap version 11.0.2. I am facing an issue where I cannot set a default value for a control. When a user selects data from a suggestive search and it gets saved in the database, I want that ...

Angular - Displaying a notification when the timezone does not align with the current moment in time

I am currently working on an angular project where users are only allowed to create tasks for today or future dates using a date picker. I have implemented the <mat-datepicker> along with moment to disable past dates. <mat-form-field formGroupNa ...

Tips on fixing the Angular error: "Argument of type '" | "" | Date' is not compatible with the parameter type 'string | number | boolean."

Currently in Angular-14, I am working on implementing a server-side search filter and pagination. Below is the code snippet that I am using: When fetching data from the web api endpoint, the startDate and endDate values are received as Date format (e.g., ...

Configuring CORS settings in Angular-cli

Upon making a request to my backend url http://docker-users:5500/users?all=true, which returns a list of users, I encountered an issue with Angular-CLI's localhost url: http://localhost:4200. Even after configuring the proxy.config.json file and addin ...

Getting the mssql output in Protractor using VSCode

I recently tried running the code below and it seems like the connection is established successfully. However, I'm unable to see any output. Is there a way to view the query result? I am still learning about Protractor, NodeJS, and MSSQL connections. ...

Having trouble getting `npm start` to work for the Lite-server?

As a newcomer to Angular and web programming, I attempted to replicate the quickstart project on github/angular by using "npm start" to initiate lite-server. However, following a tutorial [link] (https://www.youtube.com/watch?v=-zW1zHqsdyc&t=804s), I ...

Get your hands on the latest version of Excel for Angular

214/5000 I am currently facing an issue in Angular where I am attempting to generate an excel file. Within the file, there is a "Day" column that is meant to display numbers 1 through 31. However, when attempting this, only the last number (31) is being pr ...

What steps should I take to export a function from a React functional component in order to create a reusable library?

Currently, I am in the midst of developing a React component library and one of my components contains a function that I want to export. The purpose of the addParticle function is to enable users of the library to dynamically insert particles into a cont ...

Is it possible to declare two global variables with the same name in Angular?

There are two global variables that come from different third-party files with the same name. Previously, I would use them like this: declare var someVar; But now, how can I use both of these variables? declare var someVar; declare var someVar; Is th ...

Tips for guaranteeing a Typescript string enum with identical key and value pairs

I am looking for a way to create a generic type that verifies certain criteria on an enum: all fields must be strings all values must be equal to their respective keys For example, the following enums would meet the requirements: enum correct1 { bar ...

The component is failing to store its value within the database

I'm encountering an problem when attempting to save an option in the database. To address this issue, I created a component in Svelte called StatePicker that is responsible for saving US States. However, when I try to save it in the database using a ...

A guide to implementing vue-i18n in Vue class components

Take a look at this code snippet: import Vue from 'vue' import Component from 'vue-class-component' @Component export default class SomeComponent extends Vue { public someText = this.$t('some.key') } An error is being thr ...

The module 'csstype' is nowhere to be found, according to error code TS2307

I've encountered an issue with Visual Studio 2017 not compiling my code. Recently, I integrated Typescript, React, and Webpack into our solution, and everything seemed to be working fine. However, upon attempting to build our MVC application, it star ...

VSCode still throwing a replaceAll warning, despite targeting ES2021

Here is the tsconfig file for my Vue project: { "extends": "@vue/tsconfig/tsconfig.web.json", "include": ["env.d.ts", "src/**/*", "src/**/*.vue", "src/**/*.json"], "exclude ...

Ways to confirm an error message using Jest mock for throwing an error within a catch block

I'm having trouble mocking the catch block in jest for the code snippet throw Error(JSON.stringify(studentErrorRes));. While I can partially verify that an error is thrown, I'm unable to mock the error message properly. Typically, I use .mockReje ...

Executing a particular end-to-end test case using Angular 2, Karma, and Protractor

Is there a specific command I can use to run an individual e2e test case from my test suite? If that's not possible, is there some workaround for running a specific test suite? I'm currently using Jasmine, Karma, and Protractor. To start my tes ...

Unable to access the correct item from local storage while a user is authenticated

I am facing an issue with retrieving the userid from local storage when a user is authenticated or logged in. The user id is not being fetched immediately upon logging in, and even when navigating from one page to another, it remains unavailable until I re ...