Angular Providers or Providedin

Discussão em 'Angular' iniciado por hwmaat, Outubro 23, 2024.

  1. hwmaat

    hwmaat Guest

    I just can't seem to find the right way on how to use providers and provided in in Angular. I really did read the documentation on the subject, but there is a basic thing I just cannot get clear.

    Suppose I have a service my.service.ts as below where I use ProvidedIn:'root'

    import { Injectable } from '@angular/core';
    @Injectable({
    providedIn: 'root'
    })
    export class MyService {

    constructor() {
    }
    public Addup(a:number, b:number) : number
    {
    return a+b;
    }
    }


    I want that service to be available in the whole SPA as a singleton. I can inject that service in every module where needed all works fine. As in

    import {MyService} from '@services/my.service'
    @Component({
    ....
    })
    constructor (...
    private myService: MyService ,
    ...){}

    ngOnInit(): void {
    const c = myService.Addup(2,4);
    }


    Works all as expected. BUT, Should I also add it to the providers section of the app.module.ts? When I do so it looks like there is no difference in behaviour at all?

    app.module.ts:

    import {MyService} from '@services/my.service'
    ...
    ...
    @NgModule({
    Declarations [...],
    Imports: [...],
    providers: [MyService,....]
    }
    export class AppModule {}


    Can someone shed a light on this? Is ProvidedIn:'root' in the service the same as adding it to the providers array in the appModule?

    Thanks.

    Continue reading...

Compartilhe esta Página