Where should the API call be placed in the app.component to halt the system until the response is received and injected into the body, instead of using ngOnInit?

I am currently exploring Angular and experimenting with various features. Recently, I encountered an issue that requires me to take certain actions based on the results returned by a service before the application fully loads.

Currently, I am making a call to a 'webapi' in the code of the 'app.component.ts'. Based on the response from this API, I am hiding certain content on the website. However, I have noticed a delay in the server's response which is impacting the speed of the 'webapi', causing a delay in taking necessary actions to hide the content.

Now, instead of directly calling the API in the 'app.component', where the promise is returned and then injected into the body's CSS, I need to find a way to defer the API call until the result is received so that the system does not proceed without it.

Update:

In the 'ngOnInit()' of the 'app.component', we are calling an API that returns a true/false value. Depending on this value, a class called 'Type' is added to the document body, which controls the visibility of various elements like logos on the web page using Sass styling.

API Call

const res = app.services.getIsActiveType().toPromise();
document.body.classList.add(res.type);

Sass Styling

body {
  &.Type {
    logos {
      display: none;     
    }
   }
}

Answer №1

For those seeking initialization prior to anything being displayed, utilizing APP_INITIALIZER is essential.

An injection token that allows for the provision of one or more initialization functions.

These provided functions are injected at the start of the application and executed during app initialization. If any of these functions return a Promise or an Observable, initialization will not be completed until the Promise is resolved or the Observable is finished.

One example would be creating a factory function that loads language data or external configuration, then providing that function to the APP_INITIALIZER token. This function is run during the application's bootstrap process, ensuring that the necessary data is available upon startup.

Answer №2

Utilizing the canLoad or canActivate feature of the router can be beneficial.

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

The promise is unexpectedly fulfilled ahead of schedule without returning the expected value from an AXIOS call

My current challenge involves making a request to a service that rapidly generates multiple strings. The problem lies in returning a promise from this service, as I lack control over the string-generation process. It is crucial for me to return a promise ...

Customizable TypeScript interface with built-in default key value types that can be easily extended

One common pattern that arises frequently in my projects involves fetching values and updating the UI based on the 'requestStatus' and other associated values. type RequestStatus = | 'pending' | 'requesting' | 'succ ...

Error: Oops! The super expression can't be anything other than null or a function in JavaScript/TypeScript

I am facing an issue with class inheritance in my code. I have a class A that extends class B, which in turn extends class C. Whenever I try to create a new instance of class A within a function, I encounter the following error message: Uncaught TypeError: ...

Update the UI with changes from the BehaviorSubject after receiving the HttpClient response

I am currently working on a small service that makes a POST request to the backend. The response from this POST request should be added to a BehaviorSubject which is then used in various parts of the Angular application. While I can see a new record being ...

Custom React components are not designed to handle multiple onClick events simultaneously

One of my custom button components looks like this: export const Button = ({ children, onClick, className, ...props }: IButton) { const [selected, setSelected] = React.useState('primary') const handleSelected = () => { setSele ...

A Typescript function will only return a partial if the parameter passed into it is also

I have a function that takes a camelCase object and returns the same object in snake_case format. // Let's consider these types interface CamelData { exempleId: number myData:string } interface SnakeData { exemple_id: number my_data: stri ...

Angular Error: Potential security risk detected in resource URL context due to unsafe value being used

Hey there, I'm looking to display a dynamic pdf file. Initially, I encountered a CORS error, but managed to resolve it by using DOM Sanitizer. However, now I'm facing an issue with unsafe URLs. Any assistance would be greatly appreciated. Below ...

How to Nest Interfaces in TypeScript

I'm just starting to learn about Angular and I am having trouble getting the interface class to work properly. export interface Header { parentTitles: string; childHeaders: ChildHeader[]; titleIcon: string; url: string; } export interf ...

Guidelines for converting an array into checkboxes using React Native with TypeScript

As I embark on my React Native journey, I have chosen to use TypeScript in my project. Currently, I am faced with the challenge of mapping an array into a checkbox. Enclosed below is a snippet from my JSON file: { "stud_name": "Adam", "sex": "male" ...

Error TS2532 in TypeScript indicates that there is a possibility that the object is undefined

Yesterday, WebStorm 2020.1 was installed on my computer. All of a sudden, I started encountering numerous TS2532 errors. How is it even possible for this to be "undefined"? Doesn't selectedOwner && prevent that? I attempted to eliminate thi ...

NG Serve crashes after the second modification in the code

The project currently employs Angular 12.1.2. Running ng version produces the following output: Angular CLI: 12.1.2 Node: 14.17.0 Package Manager: yarn 1.22.5 OS: win32 x64 Angular: 12.1.2 ... animations, cdk, cli, common, compiler, compiler-cli, core ... ...

I possess a dataset and desire to correlate each element to different elements

[ { "clauseId": 1, "clauseName": "cover", "texts": [ { "textId": 1, "text": "hello" } ] }, { "clauseId": 3, "clauseName": "xyz", "te ...

What is the best way to search and sort a MatTable with special characters like accents and diacrit

I need to implement a name filtering functionality for a table, regardless of whether the user includes accents or not. For instance: If the user types "hydrogen", the result should display "Hydrôgen" from the table. I am using Angular 8.1.3 and Angula ...

What are the requirements for loading styleUrls in an Angular component?

How can I implement multiple CSS files in the styleUrls array? @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: [conditional statement for loading specific CSS] }) I have attempted it before, bu ...

Discrepancy detected in AGM Map printout

When attempting to print my Angular AGM Map from Chrome, I noticed a large grey gap in the map. This gap is visible even when "background graphics" are turned off and it causes the map image below it to shift downwards. If you want to reproduce this issue ...

Bringing elements into perfect harmony in Angular

Seeking guidance on HTML alignment using bootstrap for prebuilt components like buttons. Struggling with aligning divs and looking to learn more about grouping them together for proper alignment. Goal is to center elements on screen one above the other. ...

Angular is unable to bind with 'dragula' because it does not recognize it as a valid property of 'ul'

I've been attempting to incorporate dragula into my Angular 2 application, but I'm struggling to get it functioning. This is what I have added in my app.module.ts file: import { DragulaModule, DragulaService } from 'ng2-dragula/ng2-dragula ...

error: encountering issue with Vue TypeScript Jest tests - '$store' property is undefined

I've been facing issues with my tests failing after a recent npm install. I've tried adjusting versions up and down, but haven't had any success. Interestingly, the $store isn't directly used in any of the components or tests. Despit ...

Unable to navigate using react-router after logging out without a page refresh

In my logout approach, everything seems to work fine - there are no errors in the console, localHistory is cleared successfully, but for some reason it cannot navigate to the login page without refreshing the current page. const handleLogout = () => { ...

Using leaflet-markercluster in Angular 2 with Leaflet

Having some trouble trying to configure leaflet with the leaflet-markercluster plugin using angular 2. Although I've managed to make it work with angularJS in the past, I'm facing issues in angular and could use some guidance on what might be cau ...