Angular Service: Same instance vs Different instance of a service

Services are considered as singletons - same instance of the service is used across the application. This behavior is specified by "ProvidedIn" property of the Injector decorator.

Services: Same instance

Using { providedIn: "root", } in Injectable decorator in a service file during its creation and accessing the service by Dependency Injection at the component level. Any component in the application will have the same instance of the service.

@Injectable({ providedIn: "root", })

A new behavior was introduced in newer version of Angular. It introduced "[providers]" at component level since the "providers" was introduced at component level. This creates a different instance of the service that we import in [providers].

Services: Different instances

Remove { providedIn: "root"} from the Injectable decorator in the service file and add [providers] at component level. So, each component that has its own [providers] at component level has different instances of the same service.

@component({

selector: "app-first",

templateUrl: "./my.component.html",

styleUrls: ["./my.component.scss"],

providers: [Service],

})

So, we have two ways of using the services in Angular



To view or add a comment, sign in

More articles by Hemanth Kumar

  • Basic components of an effective prompting

    The 3 basic components of an effective prompt are: 1) Role (Who the AI should act as) This tells the AI what…

    2 Comments
  • AI Agent Architecture Overview

    This diagram shows a complete AI agent architecture—how a user request travels through an API, reaches the LLM, and how…

  • AI Threshold

    What is a threshold (simple definition) In AI similarity search, a threshold is a minimum similarity score required for…

  • AI Prompting Techniques

    Prompting is the art of telling an AI what to do and how to do it using natural language (and sometimes examples…

  • AI Context Window

    A context window is basically the AI’s short-term memory size during a conversation. More clearly 👇 What it means The…

    1 Comment
  • Server Sent Events - SSE

    In today’s world of real-time applications—think live dashboards, notifications, or collaborative tools—developers…

  • Libuv: non-blocking I/O in nodejs

    is a multi-platform C library that provides asynchronous I/O and other system-level functionalities to Node.js.

  • Large Language Model(LLM) and its role in solving problems in modern age

    LLM stands for "Large Language Model." It is a type of artificial intelligence designed to understand and generate…

  • Javascript: Free Resources

    ❌Don’t pay 💰 for 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 courses you can learn here for free. 𝗣𝗿𝗼𝘃𝗶𝗱𝗶𝗻𝗴 𝘁𝗵𝗲…

  • Angular and its key features

    Angular is a popular open-source web application framework developed and maintained by Google. It is primarily used for…

Explore content categories