how to inject API_BASE_URL (a string) in an angular service

后端 未结 3 1831
小鲜肉
小鲜肉 2021-01-01 21:31

this autogenerated service (by NSwagStudio) needs an API_BASE_URL (InjectionToken) value in order to perform http requests how and where i can inject it?

/*         


        
相关标签:
3条回答
  • 2021-01-01 21:49

    THe best practice to put all constants in environment.ts and environment.prod.ts. Just create a new property their and import in your service. Your code will look like this:

    // environment.ts
    export const environment = {
      production: false,
      API_BASE_URL: "baseUrlOfApiForDevelopment",
    };
    
    // environment.prod.ts
    export const environment = {
      production: false,
      API_BASE_URL: "baseUrlOfApiForProduction",
    };
    

    Now you need to import in your service to use it.

    0 讨论(0)
  • 2021-01-01 22:10

    As mentioned above, best is to put this in your environment settings then Angular will replace the appropriate base url depending on the environment you're in, e.g. in dev:

    export const environment = {
    
        production: false,
        apiRoot: "https://localhost:1234",
    };
    

    Then you can just use useValue in your provider (everything else removed for simplicity):

    ...
    import { environment } from '@env/environment';
    
    @NgModule({
    
        imports: [ ... ],
    
        declarations: [ ... ],
    
        providers: [
    
            {
                provide: API_BASE_URL,
                useValue: environment.apiRoot
            },
            ...
        ]
    
        exports: [ ... ]
    })
    export class AppModule {}
    

    To use the @env alias as shown above you need to make an addition to the tsconfig.json as follows:

    {
        ...
        "compilerOptions": {
            "baseUrl": "src",
            "paths": {
                "@env/*": [ "environments/*" ]
            },
        etc...
    }
    

    And Angular will replace the corresponding environment settings depending on the ---env flag used.

    0 讨论(0)
  • 2021-01-01 22:13

    On the parent module create a provider for API_BASE_URL

    export function getBaseUrl(): string {
      return AppConsts.baseUrl;
    }
    
    @NgModule({
      declarations: [AppComponent],
      imports: [BrowserModule],
      providers: [{ provide: API_BASE_URL, useFactory: getBaseUrl }],
       bootstrap: [AppComponent]
    })
    export class AppModule {}
    

    and then define a AppConsts class with static properties as such

    export class AppConsts {
      static baseUrl = "your_api_base_url"; 
    }
    

    Worked for me, hope it help. This solution is based on aspnet boilerpate angular project, which for me give the best standards on architecture. I leave you here the url for the angular project + the url for this specific code.

    0 讨论(0)
提交回复
热议问题