Full Trust European Hosting

BLOG about Full Trust Hosting and Its Technology - Dedicated to European Windows Hosting Customer

European Visual Studio 2022 Hosting - HostForLIFE :: Use Endpoints Explorer with .http Files in Visual Studio

clock January 17, 2025 07:07 by author Peter

Through the integration of Endpoints Explorer, a potent tool that functions flawlessly with.http files, Visual Studio 2022 has completely transformed API testing. This combination removes the need for third-party tools like Postman or Swagger by enabling developers to design, administer, and run API tests straight from the IDE.

With Endpoints Explorer, developers enjoy.

  • Reduced Context Switching
  • Increased Productivity
  • Streamlined API Testing Workflow

What Problem Does It Solve?
Before this feature, developers relied heavily on external tools to test their APIs. This involved.

  • Exporting endpoints or configurations manually.
  • Managing additional setups outside their IDE.

Endpoints Explorer fixes this by embedding API testing into Visual Studio, making the process smooth and time-efficient.

How to use Endpoints Explorer?
Open Your Project

Ensure you are using Visual Studio 2022 version 17.6 or later and load your project.

Access Endpoints Explorer
Navigate to View -> Other Windows -> Endpoints Explorer.


This tool scans your project for,

  • Controllers marked with the [ApiController] attribute.
  • Minimal API configurations.

You’ll see a comprehensive list of all available endpoints.

Working with Endpoints
Right-clicking an endpoint in the explorer provides two options.

Option 1. Open in Editor
This opens the corresponding controller or minimal API definition in the code editor. Perfect for quick reviews and edits.

Option 2. Generate Request
Selecting this option generates an API request in a .http file, enabling you to test the endpoint directly in Visual Studio.

Working with .http Files

  • If a .HTTP file (named after your project) exists, a new request is added to it.
  • Otherwise, a new .http file is created automatically.

Writing and Sending HTTP Requests
The .HTTP file is where you create and send requests. It supports:

  • GET, POST, PUT, DELETE requests.
  • Custom headers, query parameters, and JSON payloads.

Here’s an example of a request.
### Fetch all users
GET https://your-api-url.com/users
Authorization: Bearer YOUR-TOKEN

### Add a user
POST https://your-api-url.com/users
Content-Type: application/json

{
"name": "John Doe",
"email": "[email protected]"
}

Benefits of Endpoints Explorer + .http File Combo

  • All-in-One Workflow: No need to switch between IDE and external tools like Postman.
  • Collaboration Made Easy: Share .HTTP files with your team as part of your repository for consistent API testing.
  • Integrated Experience: Quickly debug endpoints and iterate through development with minimal disruptions.
  • Simpler Configuration: Directly test APIs without exporting Postman collections or Swagger setups.

Best Practices for Using Endpoints Explorer

  • Organize Requests: Group your .http requests by features or endpoints to keep your testing structured.
  • Leverage Comments: Add meaningful comments in .HTTP files to describe each request.
  • Commit .http Files to Source Control: Share and track changes with your team to maintain consistency.

Conclusion
Visual Studio 2022 revolutionizes API testing by providing developers with a quicker, more effective workflow with the use of Endpoints Explorer and.http files. For more productivity, embrace the integrated experience and bid adieu to extraneous tools. All set to give it a try? Upgrade to Visual Studio 2022 (version 17.6 or above) and start exploring the world of smooth API testing right now! Do you know how to use Endpoints Explorer? Tell us about your experience in the space provided here.



AngularJS Hosting Europe - HostForLIFE :: Configure Build Environments With Angular

clock January 10, 2025 06:47 by author Peter

Configuring build environments in Angular is essential for managing different settings and configurations for development, staging, production, or any other environments. Angular provides a built-in mechanism for this via the angular.json file and the environments folder.


Here are steps to configure build environments in an Angular application.

Step 1. Create project
ng new my-angular-app

Step 2. Create Environment Files
Angular typically comes with two environment files out of the box.
src/environments/environment.ts (for development)
src/environments/environment.prod.ts (for production)

You can create additional files for other environments (e.g., staging).

Each file exports an object with environment-specific properties.
// environment.ts (development)
export const environment = {
  production: false,
  apiBaseUrl: 'http://localhost:4000/api',
};

// environment.prod.ts (production)
export const environment = {
  production: true,
  apiBaseUrl: 'https://api.example.com',
};

// environment.staging.ts (staging)
export const environment = {
  production: false,
  apiBaseUrl: 'https://staging-api.example.com',
};


Step 3. Configure File Replacements
Modify the angular.json file to specify file replacements for different build configurations.

Locate the fileReplacements section under the configurations key in your Angular project.
"configurations": {
  "production": {
    "fileReplacements": [
      {
        "replace": "src/environments/environment.ts",
        "with": "src/environments/environment.prod.ts"
      }
    ]
  },
  "staging": {
    "fileReplacements": [
      {
        "replace": "src/environments/environment.ts",
        "with": "src/environments/environment.staging.ts"
      }
    ]
  }
}


Step 4. Add Build Scripts
Update the angular.json file to define build configurations for new environments.
"architect": {
  "build": {
    "configurations": {
      "production": {
        ...
      },
      "staging": {
        "fileReplacements": [
          {
            "replace": "src/environments/environment.ts",
            "with": "src/environments/environment.staging.ts"
          }
        ],
        "optimization": true,
        "outputHashing": "all",
        "sourceMap": false,
        "extractCss": true,
        "namedChunks": false,
        "aot": true,
        "buildOptimizer": true,
        "budgets": [
          {
            "type": "initial",
            "maximumWarning": "2mb",
            "maximumError": "5mb"
          }
        ]
      }
    }
  }
}

Step 5. Build for Specific Environments
Use the --configuration flag to build for specific environments.
ng build --configuration=staging
ng build --configuration=production


For development, the default build configuration applies unless overridden.

Step 6. Use Environment Variables in Code
In your Angular code, use the environment object to access environment-specific values.
import { environment } from '../environments/environment';
console.log('API Base URL:', environment.apiBaseUrl);
if (environment.production) {
  console.log('Running in production mode');
}


Step 7. Add Additional Settings
For complex builds, you can.

  • Use environment variables with tools like dotenv for dynamic replacements.
  • Integrate third-party CI/CD tools to manage deployment-specific configurations.

By following these steps, you can manage multiple build environments efficiently in your Angular application. Let me know if you'd like further assistance or an example.



AngularJS Hosting Europe - HostForLIFE :: TypeScript command 'tsc' not running in Terminal and PowerShell

clock December 17, 2024 06:08 by author Peter

When we run a typescript version checking command,
tsc -v

We may get error in either PowerShell prompt or Visual Studio or VS Code terminal, such as

However, if we run this same command from a command line prompt, such as Windows Colose, we can get the result:

We can see something like this

There are some articles to discuss this issue, but most of them went to a wrong answer. Actually, it is not true. From the PowerShell window, we can see:

The execution policy isn't a security system that restricts user actions. For example, users can easily bypass a policy by typing the script contents at the command line when they cannot run a script. Instead, the execution policy helps users to set basic rules and prevents them from violating them unintentionally.

Such as

The default for local Machine is Restricted

That is the reason that we cannot run the 'tsc' command from PowerShell or Visual studio and VS code terminal.

How to Fix?
Set it to ByPass:

You must be an admin role when opening the prompt:

Or



AngularJS Hosting Europe - HostForLIFE :: Connecting Angular Frontend to MongoDB via Express Backend

clock December 9, 2024 06:32 by author Peter

MongoDB With Angular Sample
Connecting MongoDB with an Express backend and an Angular frontend involves several steps. Here's a detailed guide, including a code sample, input/output, and steps.

Step 1. Set Up MongoDB
Install MongoDB

  • Install MongoDB locally or use a cloud solution like MongoDB Atlas.
  • Start the MongoDB server.

Create a Database

  • Use the MongoDB shell or a GUI tool like MongoDB Compass to create a database, e.g., my_database.
  • Add a collection, e.g., users.

Step 2. Create an Express Backend
Initialize the Project
mkdir express-mongodb-app
cd express-mongodb-app
npm init -y
npm install express mongoose body-parser cors


Create the Server File: Create a file named server.js.
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const cors = require('cors');
const app = express();

// Middleware
app.use(cors());
app.use(bodyParser.json());

// MongoDB Connection
mongoose.connect('mongodb://localhost:27017/my_database', {
    useNewUrlParser: true,
    useUnifiedTopology: true,
}).then(() => console.log("MongoDB connected"))
  .catch(err => console.error(err));

// Define Schema and Model
const userSchema = new mongoose.Schema({
    name: String,
    email: String,
});
const User = mongoose.model('User', userSchema);
// Routes
app.get('/api/users', async (req, res) => {
    const users = await User.find();
    res.json(users);
});
app.post('/api/users', async (req, res) => {
    const newUser = new User(req.body);
    await newUser.save();
    res.status(201).json(newUser);
});
// Start Server
const PORT = 3000;
app.listen(PORT, () => {
    console.log(`Server running on http://localhost:${PORT}`);
});

Run the Server
node server.js

Step 3. Create the Angular Frontend

Set Up Angular Project
ng new angular-mongodb-app
cd angular-mongodb-app
ng add @angular/material
npm install axios

Service for API Communication: Create a file src/app/services/user.service.ts.
import { Injectable } from '@angular/core';
import axios from 'axios';
@Injectable({
    providedIn: 'root'
})
export class UserService {
    private baseUrl = 'http://localhost:3000/api/users';
    getUsers() {
        return axios.get(this.baseUrl);
    }
    addUser(user: { name: string; email: string }) {
        return axios.post(this.baseUrl, user);
    }
}


Component for User Interaction: Update src/app/app.component.ts.

typescript

import { Component, OnInit } from '@angular/core';
import { UserService } from './services/user.service';

@Component({
    selector: 'app-root',
    template: `
        <div style="text-align: center;">
            <h1>Angular with Express & MongoDB</h1>
            <form (submit)="addUser($event)">
                <input type="text" [(ngModel)]="name" placeholder="Name" name="name" required>
                <input type="email" [(ngModel)]="email" placeholder="Email" name="email" required>
                <button type="submit">Add User</button>
            </form>
            <ul>
                <li *ngFor="let user of users">{{ user.name }} ({{ user.email }})</li>
            </ul>
        </div>
    `,
    styles: []
})
export class AppComponent implements OnInit {
    users: any[] = [];
    name = '';
    email = '';

    constructor(private userService: UserService) {}

    ngOnInit() {
        this.loadUsers();
    }

    async loadUsers() {
        const response = await this.userService.getUsers();
        this.users = response.data;
    }

    async addUser(event: Event) {
        event.preventDefault();
        await this.userService.addUser({ name: this.name, email: this.email });
        this.loadUsers();
        this.name = '';
        this.email = '';
    }
}


Install Angular Forms Module: Add FormsModule to AppModule.
typescript
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
@NgModule({
    declarations: [AppComponent],
    imports: [BrowserModule, FormsModule],
    providers: [],
    bootstrap: [AppComponent]
})
export class AppModule {}


Run the Angular Application
ng serve

Step 4. Input and Output
Input

Fill the form with a name and email, e.g.
Name: "Peter Scott"
Email: "[email protected]"

Output: The list below the form will update to include the newly added user.

less
Peter Scott ([email protected])

Step 5. Visual Workflow (Images)
Backend (server.js)

  • Database schema for storing user data.
  • APIs (/api/users) for CRUD operations.


Frontend (Angular App)

  • The user fills out the form.
  • Data is sent to the Express backend.
  • Data is saved in MongoDB.
  • Users are displayed dynamically.


AngularJS Hosting Europe - HostForLIFE :: Convert Doc to Pdf using NodeJS

clock December 5, 2024 08:53 by author Peter

To convert a DOC file to PDF using Node.js and PowerShell, you can use the following steps:
Install the ‘child_process’ package in your Node.js project by running the following command in your project’s terminal:

npm i child_process

Create a PowerShell script that converts the DOC file to PDF using Microsoft Word. You can use the following script:
$documents_path = 'C:\Users\Peter\Downloads\DoctoPdf\doc\Web_Service_Uing_Ajax_in_net.docx'
$output_path = 'C:\Users\Peter\Downloads\DoctoPdf\doc\Web_Service_Uing_Ajax_in_net12.pdf'
$word_app = New-Object -ComObject Word.Application
# This filter will find .doc as well as .docx documents
Get-ChildItem -Path $documents_path -Filter *.doc? | ForEach-Object {
    $document = $word_app.Documents.Open($_.FullName)
    $pdf_filename =  "$output_path"
    $document.SaveAs($pdf_filename)
    $document.Close()
}
$word_app.Quit()
return $output_path

Make sure to replace the input and output file paths with the actual paths to your files.
Use the ‘child_process’ package in your Node.js code to execute the PowerShell script. You can use the following code:
    const express =  require('express');
    const app =  express();
    const port = 5000;
    const { exec } = require('child_process');
    const { v4: uuidv4 } = require('uuid');
    const fileUpload = require('express-fileupload');
    const fs = require('fs');
    app.use(express.json({
        limit: "200mb"
      }));
      app.use(
        express.urlencoded({
          extended: true,
          limit: "200mb",
        })
      );


    app.use(fileUpload());

    app.post('/', function(req, res,next){
        console.log('req', req.files.inputfile)

        let uploaded_path = __dirname+'/doc/' + req.files.inputfile.name;
        fs.writeFile(uploaded_path, req.files.inputfile.data, function(err) {
            if(err) {
                return console.log(err);
            }
            ///console.log("The file was saved!");
            const cmd = `$documents_path = "${uploaded_path}"
            $output_path = '${__dirname}/doc/${uuidv4()}.pdf'
            $word_app = New-Object -ComObject Word.Application
            # This filter will find .doc as well as .docx documents
            Get-ChildItem -Path $documents_path -Filter *.doc? | ForEach-Object {
                $document = $word_app.Documents.Open($_.FullName)
                $pdf_filename = "$output_path"
                $document.SaveAs([ref] $pdf_filename, [ref] 17)
                $document.Close()
            }
            $word_app.Quit()
            return $output_path`;
            exec(cmd, {'shell':'powershell.exe'}, (error, stdout, stderr)=> {
                console.log('Error', stderr)
                   console.log('OUTPUT', stdout);
                   res.status(200).json({status:200, msg:"success", stdout: stdout})
            })
        });

    })


    app.listen(port, function(){
        console.log('Server is running on port', port);
    })


Make sure to replace the script path and input file path with the actual paths to your files.
Run your Node.js code and the DOC file will be converted to PDF using PowerShell. The output PDF file will be saved to the path specified in the PowerShell script.



AngularJS Hosting Europe - HostForLIFE :: How Can I Use the Angular 18 Component to Call a JavaScript Function?

clock November 29, 2024 08:39 by author Peter

In this walk, you will learn about running and calling javascript functions from the Angular component.

How it’s implemented and what is the description?

  • Create Angular project - AnguWalk.
  • Run the application and check that the project was created successfully.
  • Create JS file with function.
  • Adding JS file link/reference to angular.json
  • Component (TS file) coding.
  • Execute the Project
  • Output

Create an Angular Project called “AnguWalk” using the following CLI command.Commandng new AnguWalkBashExample

Go inside the project folder and open the Visual Studio code.

Command
cd anguwalk
<enter>
code .
<enter>

Example

Note. Visual Studio code will get started only if your system is configured with path and settings.

Create Javascript file

  • First, create a JS folder inside the SRC folder.
  • Right-click on SRC and select the option New Folder.

    function HelloMsg(arg) {
        alert("Welcome to Angular Class - " + arg);
    }

Reference JS File in angular.json file
The Angular.json file is located inside the project root folder. Open and update the SCRIPTS array which is inside the builds object.

"scripts": [
    "src/js/WelcomeMsg.js"
]


Open app.component.html and update the code.

Note. Remove the default code of app.component.html.
import { Component, OnInit } from '@angular/core';
import { RouterOutlet } from '@angular/router';

declare function HelloMsg(arg: any): void;

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [RouterOutlet],
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {

  ngOnInit() {
    HelloMsg("Peter, Scott");
  }

  title = 'AnguWalk';
}

Now, run the project to check the output.

Command
ng serve --open

Output


You see the javascript HelloMsg function executed and the alert window displayed successfully. Happy Coding!



AngularJS Hosting Europe - HostForLIFE :: Debugging Angular Using Visual Studio Code

clock November 12, 2024 06:06 by author Peter

This brief post is meant for readers who are using Visual Studio Code to work on an Angular project and are having trouble adding a debugger. When I first started using Visual Studio Code to debug Angular projects, I thought it was rather strange, but eventually I thought it was cool. I discovered that many users were asking how to debug an Angular project in Visual Studio Code. I therefore considered composing this brief piece.

Note: I created and executed my Angular project, which internally uses WebPack, using the Angular CLI.

Step by Step add debugger in Visual Studio Code
Open your Angular project in Visual Studio Code.

Install Extension, as shown below.

Click Debug icon & Add Configuration, as shown below.

Select Chrome and add the configuration given below in launch.json file (This file gets created in .vscode folder).
{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Launch Chrome against localhost",
            "type": "chrome",
            "request": "launch",
            "url": "http://localhost:4200",
            "sourceMaps": true,
            "webRoot": "${workspaceRoot}",
            "sourceMapPathOverrides": {
                "webpack:///./*": "${workspaceRoot}/*"
            }
        }
    ]
}

Open command terminal. As I am using Angular CLI to run my Angular project. I am using
> ng serve
command to build and run my application. By default, it runs on port 4200 (Same port is mentioned in my launch.json file).

Now, your development Server is running. Now, you can press F5 or play icon in the debug tab. Keep the break point and it will hit the .ts file.

Note.You may be surprised how JS can map my .ts file in code and debugger can hit my .ts file. This is because of "sourceMaps": true setting in launch.json. Similarly, we can add more debugger by adding an extension and then configuring in same launch.json file. I hope, this small article will be helpful to you. Please do comment, whether it’s good or bad. Sharing is valuable. Thank you for reading and have a great day.



AngularJS Hosting Europe - HostForLIFE :: Apply "Go to Bottom" and "Go Up" on Click of Anchors

clock November 5, 2024 08:47 by author Peter

In this article, I will tell you how to apply "Go to Bottom" and "Go Up" with a click of Anchors in an application. We often create single-page applications that are in great demand at the present time. In these applications, you might need a functionality by which the user can go to a different part of a page just by clicking on the link and not by scrolling. To do this kind of functionality, you can use AngularJS.


Now, I will create an application that will help you to create such an application.

Step 1. First of all, you need to add an external Angular.js file to your application, "angular.min.js". For this, you can go to the AngularJS official site or download my source code and then fetch it, or you can click on this link and download it: ANGULARJS. After downloading the external file, you need to add it to the Head section of your application.

<head runat="server">
    <title></title>
    <script src="angular.min.js"></script>
</head>


Step 2. Now, after adding the external JS file, the first thing you need to do is to add ng-app in the <HTML> Tag; otherwise, your application will not run.
<html ng-app xmlns="http://www.w3.org/1999/xhtml">


Now, I will create a simple application that will help you understand this feature.

First I will create a JavaScript function, this is the heart of this article. All the things will be described in this function.
<script>
    function x($scope, $location, $anchorScroll) {
        $scope.goDown = function () {
            $location.hash('down');
            $anchorScroll();
        };

        $scope.goUp = function () {
            $location.hash('up');
            $anchorScroll();
        };
    }
</script>


Here I have created a function named "x", but today in the function $location and $anchorScroll are also used along with $scope. $location service parses the browser address bar and makes the URL available to your application.

Then I created a function that will help the user to go down just with the click of a link, this function is named "goDown". In this function a hash method is used with location, you can't change the "hash" method with any other variable name, it's fixed, and this has the method id of control that is passed to be followed on the click of the anchor.

Similarly, I have created a function that will help the user to go up, here also the hash method is used and in this method, the name of the control is passed that is to be followed when clicking the anchor.

Step 3. Our work on the View is completed, and now I will work on the View Model of this application.
<body>
    <form id="form1" runat="server">
        <div ng-app="App">
            <div id="div" ng-controller="x">
                <div style="color: green;">
                    <a id="up" ng-click="goDown()">Go Down</a>
                </div>
                <div style="color: red;">
                    <a id="down" ng-click="goUp()">You're at the bottom</a>
                </div>
            </div>
        </div>
    </form>
</body>


Here a div is bound to the function "x" using the ng-controller, in this div again two divs are created. In both the div anchors are used, the first anchor is bound to the "goDown" function using the ng-click, and the second anchor is also bound using the ng-click but it is bound to the group function.

Some style is also applied to this application, this style will help to show the two anchors at a specific distance by which only one will be seen at a time and the second one will only be seen when the user clicks on the anchor.

Now, our application is created and is ready for execution.

Output
Now, if we run our application, then we will get output like this.

You can see that only one anchor can be seen at this time and in other words the first anchor, now if we click on the first anchor then our page will go down to the element that was called using the JavaScript function.

Complete Code
The complete code of this application is as follows.
<html ng-app xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="angular.min.js"></script>
    <script>
        function x($scope, $location, $anchorScroll) {
            $scope.goDown = function () {
                $location.hash('down');
                $anchorScroll();
            }
            $scope.goUp = function () {
                $location.hash('up');
                $anchorScroll();
            }
        }
    </script>
    <style>
        #div {
            height: 350px;
            overflow: auto;
        }
        #down {
            display: block;
            margin-top: 2000px;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
        <div ng-app="App">
            <div id="div" ng-controller="x">
                <div style="color:green;">
                    <a id="up" ng-click="goDown()">Go Down</a>
                </div>
                <div style="color:red;">
                    <a id="down" ng-click="goUp()">You're at the bottom</a>
                </div>
            </div>
        </div>
    </form>
</body>
</html>

 



European Visual Studio 2022 Hosting - HostForLIFE.eu :: Endpoint Explorer in Visual Studio 2022

clock October 29, 2024 08:59 by author Peter

We can test our APIs with a new capability in Visual Studio 2022. If Swagger is not available, we can test and experiment with the API's endpoints using Endpoint Explorer from Visual Studio.


Procedures

As shown in the screen below, open any API project and select View->Other windows->Endpoint Explorer.

After opening Endpoint Explorer, we have the left window from where we can see all the listed API endpoints in applications.


Let’s Invoke
Right-click on the endpoint and click on Generate Request.


We will have the window below. We can click on the send request button and get a response.

We will get a response in the new window as below.


GET by ID. I have updated the ID as per the request URL and got the corresponding response.


Next Step
We can save this above middle window as a file with a .http extension and can use it next time without going to Endpoint Explorer. We can say this file is a ready-made rest client for playing and testing our endpoint.

I saved the above file and used the next file for testing purposes. Thanks



AngularJS Hosting Europe - HostForLIFE :: IoC Providers in Angular Dependency Injection useClass

clock October 9, 2024 09:04 by author Peter

Manual Injection of Class
Before we dive deep into Angular providers, let’s see how to create an Angular provider by ourselves. Please take a look at the below screenshot. We have created an interface named IManualService. We have two classes implementing the IManualService interface: ManualService and ManualServiceWithLog.

import { InjectionToken } from '@angular/core';
export const MANUAL_SERVICE_TOKEN = new InjectionToken<IManualService>(
  'MANUAL_SERVICE_TOKEN'
);
interface IManualService {
  name: string;
}
export class ManualService implements IManualService {
  public name = 'Manual Service';
  constructor() {}
}
export class ManualServiceWithLog implements IManualService {
  public name = 'Manual Service with logging feature';
  constructor() {
    console.log('I am manual service class with logging feature');
  }
}


For the dependency injection to work, we need to take care of three steps.
Define a Token: Define a token with a name for the injection. The token name is used by IoC to identify the class that needs to be injected whenever the particular token is requested.
    export const MANUAL_SERVICE_TOKEN = new InjectionToken<IManualService>(
      'MANUAL_SERVICE_TOKEN'
    );


Provide the Injection: The provider is the place where we define which class/value needs to be provided whenever we are requesting for a class/value.

Injecting ManualService class

import { ApplicationConfig } from '@angular/core';
import { provideRouter } from '@angular/router';

import { routes } from './app.routes';
import {
  MANUAL_SERVICE_TOKEN,
  ManualService,
  ManualServiceWithLog,
} from './services/manual-service/manual-service';

export const appConfig: ApplicationConfig = {
  providers: [
    provideRouter(routes),
    {
      provide: MANUAL_SERVICE_TOKEN,
      useClass: ManualService,
    },
  ],
};

Injecting ManualServiceWithLog class
import { ApplicationConfig } from '@angular/core';
import { provideRouter } from '@angular/router';

import { routes } from './app.routes';
import {
  MANUAL_SERVICE_TOKEN,
  ManualService,
  ManualServiceWithLog,
} from './services/manual-service/manual-service';

export const appConfig: ApplicationConfig = {
  providers: [
    provideRouter(routes),
    {
      provide: MANUAL_SERVICE_TOKEN,
      useClass: ManualServiceWithLog,
    },
  ],
};

Inject the Token: Inject the token in our component or elsewhere wherever we are using it.
constructor(
   @Inject(MANUAL_SERVICE_TOKEN) private manualService: ManualService
 )

import { Component, Inject, Injectable } from '@angular/core';
import {
  MANUAL_SERVICE_TOKEN,
  ManualService,
} from '../services/manual-service/manual-service';

@Component({
  selector: 'app-books-cart',
  standalone: true,
  imports: [],
  templateUrl: './books-cart.component.html',
})
export class BooksCartComponent {
  value: string = '';
  constructor(
    @Inject(MANUAL_SERVICE_TOKEN) private manualService: ManualService
  ) {
    this.value = manualService.name;
  }
}


Once we take care of the above steps, we are ready with dependency injection. Since I am using Angular 18, the latest version, I am using app.config.ts to configure the providers. Here in this app.config.ts, for the key MANUAL_SERVICE_TOKEN, I am passing the ManualService class.

You can see the name ‘Manual Service’ populating from the ManualService class being printed in the UI. In the app.routes.ts class, instead of passing the ManualService class, if you pass the ManualServiceWithLog class, you can see that name being printed as ‘Manual Service with Logging Feature’. Along with that, we can even observe that the console is being logged.

UI Output while using ManualService Class


UI Output while using ManualServiceWithLog.


I hope from this example, you have understood how to use Dependency Injection in Angular and the use of useClass in providers.



About HostForLIFE

HostForLIFE is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.

We have offered the latest Windows 2019 Hosting, ASP.NET 5 Hosting, ASP.NET MVC 6 Hosting and SQL 2019 Hosting.


Tag cloud

Sign in