Angular 2 when to use DI, provider or pure import?

Discussão em 'Angular' iniciado por Teddy, Março 24, 2025.

  1. Teddy

    Teddy Guest

    I am little confused when is proper to use what.

    1. Define class with static functions, just import and use imported name and then function

    Shared class:

    export class SomeClass {
    static someFunction(){
    ...
    }
    }


    Class which uses exported class:

    import { SomeClass } from './someclassstatic'
    ...
    constructor(){
    SomeClass.someFunction()
    }


    2. Define standard class, then mount via DI

    Shared class:

    export class SomeClassDI {
    public someFunctionDI(){
    ...
    }
    }


    Class which uses exported class:

    import { SomeClassDI } from './someclassdi'
    ...
    constructor(private theclassdi:SomeClassDI){
    this.theclassdi.someFunction()
    }


    3. Define standard class, then mount as provider while bootstraping

    Shared class:

    export class SomeClassBS {
    public someFunctionBS(){
    ...
    }
    }


    Class that bootstraps Angular2

    import { SomeClassBS } from './someclassbs'
    ...
    bootstrap(AppComponent, [SomeClassBS]);


    Class which uses exported class:

    ??? I am not sure what can be the example here.


    What is the proper use of the providers?

    Continue reading...

Compartilhe esta Página