How to make a string constant in angular 4?

后端 未结 3 1795
萌比男神i
萌比男神i 2021-02-05 11:03

In my service, I am using a http post. I want to set the URL as a constant.

return this.http.get(this.config.API_URL+\'users\', options).map(res=&g         


        
3条回答
  •  无人及你
    2021-02-05 11:33

    You can simply export a constant using es6/typescript modules if that's all you need:

    constants.ts:

    export const API_URL: string = 'api/url';
    

    And import where needed:

    import { API_URL } from './constants.ts';
    
    ...
    
    return this.http.get(API_URL+'users', options)
                    .map(res=>res.json());
    

    or if you have many constants you can import them all:

    import * as constants from './constants.ts';
    
    ...
    
    return this.http.get(constants.API_URL+'users', options)
                        .map(res=>res.json());
    

    If you want to make your constants configurable per application on startup, you can use providers. Check out the top answer in this link: how do I get angular2 dependency injection to work with value providers

提交回复
热议问题