What is the initial component that Angular will activate or run?

Uncertainty surrounds the correctness of my question. Within my application, there exist numerous routing components and feature modules. I am eager to discern whether the appcomponent.ts file or the routing logincomponent.ts file will be executed first.

As the flow of the application shifts from the frontend to the backend through a login API call (changing components based on headers), successful logins prompt the storage of pertinent details within a globally exported object, subsequently injected as a service into another component.

appcomponent.ts

constructor(private auth: AuthService, private user: User) {
  this.auth.login().subscribe((res)=>{ 
  this.user.userProps.userRole = resp.headers.get('userRole');
})
}

app.routing.module.ts

{ path: '', pathMatch: 'full', redirectTo: '/login' },
  { path: 'login', component: LoginComponent, canActivate: [RandomGuard] }

random.guard.ts

    canActivate() {
console.log(this.user.userProps); // have null value; why app component value not receiving here
        if (this.user.userProps.userRole === 'user') {
          this.router.navigate(['/user']);
        } else if (this.user.userProps.userRole === 'admin') {
          this.router.navigate(['/admin']);
        }
        return true; // So it will redirect into login
      }

login.component.ts

constructor(private user: User, private auth: AuthService, private router: Router) {
    if (this.user.userProps.userRole === '' || this.user.userProps.userRole === null) {
      this.auth.login().subscribe((resp: any) => {
        console.log(resp, 'resp');
        this.user.userProps.userRole = resp.headers.get('userRole');
        if (this.user.userProps.userRole === 'admin') {
          this.router.navigate(['/admin']); //proper routing will happen
        } else {
          this.router.navigate(['/user']);
        }
      }, (err) => {
        return false;
      });
    }
    }

auth.service.ts

login(): Observable<HttpResponse<any>> {
    return this.http.get(`${environment.baseUrl}home/login`, {observe: 'response'});
  }

My query pertains to which component's constructor gets invoked first - appcomponent or logincomponent.

Answer №1

Typically, the initial component that loads after an application is Bootstrapped is the AppComponent.

If you examine your app.module.ts, it should include:

bootstrap: [ AppComponent ] // Indicates this is loaded first

Upon reviewing your route configuration, the AppComponent will load initially and then the routing will direct you to the LoginComponent.

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

Implementing Angular 4, modifying the display to reflect changes in the latest model

Hey, I'm having some trouble with a component called 'updateUserInfo'. When I call it from a service, the value in the view doesn't change. Can someone assist me with this, please? @Component({ selector: 'app-menu', t ...

Angular Error: Unable to access properties of null (specifically 'validators')

I am encountering an issue with my Angular code where I receive the error message "TypeError: Cannot read properties of null (reading '_rawValidators')". import { Component, OnInit } from '@angular/core'; import { Wifi } from './wi ...

best practices for filtering custom data returned from valuePreparefunction in ng2 smart table

Having an issue with the filter in ng2 smart table because I am returning custom data from the valueprepareFunction. This is my setup... columns: { id: { title: 'Id', type: 'string' }, surname: { title: 'surname', ty ...

Error encountered in Angular 7.2.0: Attempting to assign a value of type 'string' to a variable of type 'RunGuardsAndResolvers' is not allowed

Encountering an issue with Angular compiler-cli v.7.2.0: Error message: Types of property 'runGuardsAndResolvers' are incompatible. Type 'string' is not assignable to type 'RunGuardsAndResolvers' This error occurs when try ...

Utilizing Ace with a personalized theme in Angular 2 application while straying away from the default theme directory

I am currently facing an issue with integrating an Ace editor into my Angular 2 application, which is built using angular-cli. I want to link the Ace editor to a custom theme stored in the app's assets folder src/app/assets instead of within node_modu ...

Is there a way to programmatically add a timestamp to a form in Angular6?

Is there a way to automatically populate new forms with the current datetime value? this.editForm.patchValue({ id: chatRoom.id, creationDate: chatRoom.creationDate != null ? chatRoom.creationDate.format(DATE_TIME_FORMAT) : null, roo ...

How can I replace this jQuery state change with the appropriate Angular code?

Within a component, I have a subject that triggers a .next(value) and initiates the following jQuery logic: if (this.isOpen) { jQuery(`#preview-${this.index}`). stop().slideDown('fast'); } else { jQuery(`#preview-${this.index}` ...

How exactly does the 'this' type in TypeScript determine its own type inferences?

When working with TypeScript, I wanted to use the this keyword to type certain properties of my class. However, I encountered a problem that I couldn't figure out how to solve. What I was trying to achieve is something like this: export class Animal{ ...

Controlling CSS Styles in Angular using TypeScript

Currently, I am working on an Angular project that involves dynamically populating a calendar. In addition to this, I have a range of dates and the task at hand is to modify the background for specific days within this date range. To manage dates effective ...

Creating a navigation bar that smoothly slides into view from the top

In my Angular app (version 2+), the current code I have is: .header { background: rgba(white, 0); &.fixed-top { background: rgba(white, 1); border-bottom: solid whitesmoke 1px; position: fixed; top: 0; right: 0; left: 0; ...

Sort by label using the pipe operator in RxJS with Angular

I have a situation where I am using an observable in my HTML code with the async pipe. I want to sort the observable by the 'label' property, but I'm not sure how to correctly implement this sorting logic within the pipe. The labels can be e ...

Utilizing Angular: Integrating the Http response output into a map

I have a situation where I am making multiple HTTP calls simultaneously from my Angular application. The goal is to store the responses of these calls in a Map. data: Map<number, any> = new map<number,any>(); --------------------------------- ...

Understanding the specific types of subclasses derived from an abstract generic class in Typescript

There is a Base generic class: abstract class BaseClass<T> { abstract itemArray: Array<T>; static getName(): string { throw new Error(`BaseClass - 'getName' was not overridden!`); } internalLogic() {} } and its inherito ...

When clicking, clear the selected items and avoid the function from repeatedly executing

I am currently facing issues with implementing mat-select-autocomplete in my project. Firstly, I have noticed that the function's (selectionChange)="getSelectedOptions($event)" is triggered every time I click on mat-select-autocomplete. Is there a wa ...

What are the reasons behind the issues encountered when enabling "Optimization" feature in Angular that affect the proper rendering of PrimeNg elements?

Angular Version : 9.x Primeng Version : 9.x We've encountered an issue with PrimeNg elements not rendering correctly in our dev/prod environments, although they work fine in the local environment. After some investigation, we found that the culprit ...

Adjusting the background opacity when the sidebar is open in a React + Typescript project

I am currently working on customizing a sidebar using the react-pro-sidebar library along with React and Typescript. The sidebar layout seems to be in order, but I am facing difficulty in adjusting the background color of the rest of the screen when the si ...

Ensuring that a date is within a certain format in TypeScript

Can someone help me verify the validity of different date formats? I attempted the following method: let newdate = new Date(myStringDate); Date.parse(myStringDate) result = `${newdate.getDate()}/${newdate.getMonth() + 1}/${newdate.getFullYear()}` The re ...

Exploring the world of Typescript, mastering tests, and diving deep into debugging

As a newcomer to Angular 2 and TypeScript, I recently created a basic application using the Angular CLI. However, I've encountered a gap in my understanding regarding how TypeScript code in VS Code translates into a functional app in a web browser. I ...

Having trouble generating a bin executable for my npm package

Referencing: https://docs.npmjs.com/cli/v10/configuring-npm/package-json#bin I am attempting to generate a "binary" for my npm package. The structure of my package.json is as follows: { "name": "@internal/my-exe", "version": "0.0.0", "type": "commo ...

Tips for accessing and manipulating an array that is defined within a Pinia store

I have set up a store to utilize the User resource, which includes an array of roles. My goal is to search for a specific role within this array. I've attempted to use Array functions, but they are not compatible with PropType<T[]>. import route ...