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

后端 未结 3 1849
小鲜肉
小鲜肉 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 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.

提交回复
热议问题