"Transitioning to a standalone setup in Angular: A step-by-step

Can someone guide me on how to transition to a standalone setup with the following requirements:

  1. I want to utilize HttpClient in ApplicationConfigService. How can I achieve this?
  2. After initializing the app, I need to use the load function.

export function initializeFn(jsonAppConfiguration: ApplicationConfigService){
  return () =>{
    return jsonAppConfiguration.load();
  };
}

Please review the code snippets below:

export abstract class AppConfiguration{
    baseUrl:string = '';
    connectionName:string = '';
}

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { AppConfiguration } from './app-config'
import { DOCUMENT } from '@angular/common';
import { Inject } from '@angular/core';

@Injectable({providedIn: 'root'})
export class ApplicationConfigService extends AppConfiguration{

  constructor(@Inject(DOCUMENT) private document: Document, private http: HttpClient) { 
    super();
  }


  load(){
    try{
    
      this.connectionName = (this.document.getElementsByName("connectionName")[0] as any).value;
      this.baseUrl = (this.document.getElementsByName("baseUrl")[0] as any).value;
    }
    catch{}
  }
}


import { APP_INITIALIZER, Component } from '@angular/core';
import { RouterOutlet } from '@angular/router';
import { ApplicationConfigService } from './config/application-config.service';
import { HttpClientModule } from '@angular/common/http';


export function initializeFn(jsonAppConfiguration: ApplicationConfigService){
  return () =>{
    return jsonAppConfiguration.load();
  };
}

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [
    RouterOutlet,
    HttpClientModule
  ],
  providers: [
    ApplicationConfigService,
    {
      provide:APP_INITIALIZER,
      multi:true,
      deps:[ApplicationConfigService],
      useFactory:initializeFn
    }
  ],
  templateUrl: './app.component.html',
  styleUrl: './app.component.scss'
})
export class AppComponent {
  title = 'f_project';
}

import { HttpClient, HttpClientModule } from '@angular/common/http';
import { ChangeDetectorRef, Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { ApplicationConfigService } from '../config/application-config.service';

@Component({
  selector: 'app-main',
  standalone: true,
  imports: [],
  templateUrl: './main.component.html',
  styleUrl: './main.component.scss'
})
export class MainComponent implements OnInit{


  public ConnectionName: string = '';



  constructor(private route: ActivatedRoute, private http: HttpClient, private AppConfig: ApplicationConfigService, private cdr: ChangeDetectorRef) {
    this.ConnectionName = AppConfig.connectionName;
  }

  ngOnInit(): void {
    console.log("ConnectionName: " + this.ConnectionName);
  }
}


Answer №1

Follow this schematic to smoothly transition

ng generate @angular/core:standalone

Source: https://angular.io/guide/standalone-migration

In a standalone module, utilize the httpModule as shown below:

@Component({
  selector: 'app-main',
  standalone: true,
  imports: [CommonModule, HttpClientModule],    // ensure it is added in the imports section
...

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

Ways to stop Harmful POST Requests in a PHP program?

I'm currently in the process of creating a website that functions similarly to an online game and features a scoring system. Upon completing specific activities, users are rewarded with virtual coins which are then stored in a SQL database through a d ...

The Bootstrap menu vanishes when tapped on mobile devices, and the header image fails to resize accordingly

After spending several hours attempting to troubleshoot on my own and seeking assistance from other online resources, I have been unsuccessful in resolving two key issues with my website. The first problem lies with the bootstrap navigation menu on www.di ...

The Shell Application is not refreshing React HtmlElement Micro Front end

I am currently facing an issue when trying to inject the following React MFE into another Angular shell application. The MFE loads successfully the first time, but if it is hidden or removed from the DOM and then reloaded, it fails to load. Could you plea ...

Issue Alert: Inconsistencies with Google Scripts spreadsheets

Objective I have been working on a script that will make consecutive calls to an API (with a JSON response) and input the data into a Spreadsheet. Issue: When I debug the script, everything runs smoothly without any major problems. However, when I try r ...

Error message: "Window is not defined in Next.js"

Can anyone help me with this issue I'm experiencing: 'window is not defined' error? useEffect(() => { const handleScroll = () => { if(typeof window !== 'undefined') { // scrolling dete ...

Warning issued by Angular 7 indicating the usage of the routerLink directive and advising against navigation triggered outside the Angular zone

Encountering difficulties while working with the Angular framework to ensure smooth functioning of my application, I am currently facing an obstacle with routing. The structure includes a main AppComponent and a app-routing.module.ts file for navigation ma ...

How can I make a recently added row clickable in an HTML table?

I have a table where each row is given the class ".clickablerow". I've set up an onclick function so that when a row is clicked, a dialog box appears allowing me to insert text above or below as a new row. The issue I'm facing is that even though ...

Having difficulty animating camera rotation in ThreeJS with Tween

I am facing an issue with animating the ThreeJS camera rotation using TweenJS. While I can successfully tween the camera position, the camera.rotation does not seem to update as expected. To illustrate my problem, I have created a simple example based on ...

Tips for extracting the correct Element from a REST API request

Trying to access a REST API that returns a JSON Object containing a session_token. I only need the session_token, but how can I extract it? this.http.post(this.tokenURL, this.tokenCall).subscribe(res => { this.token = res.session_token; }); This is ...

Request validated even though _RequestVerificationToken was not included in the AJAX request

Implementing HtmlAntiForgeryToken in an MVC application involves adding @Html.AntiForgeryToken() on the .cshtml page and including the [ValidateAntiForgeryToken] attribute in the controller. When making an AJAX POST call to the controller, it is crucial to ...

Angular Directive - Embedding Complex Objects in Attribute

Here's a fantastic solution provided for this specific question, demonstrating how to utilize a directive to showcase nested objects as <tr>'s. However, I'm aiming to take it a step further by passing a nested object into my attribute ...

Try implementing an alternative to using flatMap in JavaScript

Looking for an alternative method to achieve the same functionality as flatmap in JavaScript with lower ES5 version for the following mapping. const b = [{ "errorname": [{ "name": "Error 01", "desc_1": "Test: 01", "desc_2": "Testing" }, ...

How to use the window.confirm method to print the HTML tag in an AJAX post

Is there a way to display a confirmation window for users who want to delete data from the database without including HTML tags like <strong> or <br />? I am currently using the confirm() function as follows: var str = document.getElementById ...

Ways to showcase hierarchical list information in tabulator

I have set up a search and listing panel on my screen. To display nested data on the listing page, I decided to use tabulator. Here is the code in my js file : function onCheckClick() { var url = "/SomeController/SomeAction/"; $.ajax({ url: ...

Encountering a SyntaxError while implementing lightweight-charts in NextJS

I'm encountering an issue while trying to integrate the lightweight-charts package into my nextjs project. When attempting to utilize the createChart function, I am receiving a syntax error in my Node.js console. ...\lightweight-charts\dist& ...

Explore the simple method to redirect within a jQuery fancybox popup to the succeeding page using jQuery

I have implemented a jQuery fancy box popup window for my form submission. However, upon submitting the form, it redirects in the same popup window. I would like to redirect the page to another open window instead of the same popup. Although I tried using ...

What is the process for reaching application-level middleware from the router?

Within my project created using express application generator, I am facing a challenge accessing my application-level middleware from the router. This middleware is specifically designed to query the database using the user ID that is received from the ro ...

Is there a way to prevent nesting subscriptions in rxjs?

Currently, I am working with a code that contains nested subscribes: .subscribe((data) => { const { game, prizes } = data; this.ticketService.setListOfTickets(game.tickets); this.ticketService.getListOfTickets() .subscribe((data: any) => { ...

What is the process for sending values to a component?

I am working with a component called MyComponent: export class MyComponent { @Input() active:boolean; constructor() { console.log(this.active); } } In this component, I have declared an Input, and I pass it in as follows: <mycomp ...

Using single page anchor tags in Next.js to toggle content visibility

The Issue Currently working on a project using Next.js and facing a challenge: needing to hide or replace content based on the selected category without reloading the page or navigating to another route. Furthermore, ensuring that when the page is reloade ...