How to make a string constant in angular 4?

后端 未结 3 1800
萌比男神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:34

    Define app constant as public static readonly as below

    public static readonly constName = 'Consts Value'

    /app-constants.ts

    export class Constants {
    
         public static readonly routeAuthRegister = '/auth/register';
         public static readonly routeAuthLogin = '/auth/login';
         public static readonly routeAuthRecovery = '/auth/forgot-password';
    
    }
    

    /api-constants.ts

    It's better to keep your base URI's in enverment files. and define your environments in apps in .angular-cli.json. i here attache screen shot below for define custom app environments .

    import { environment } from '../../environments/environment';
    
    export class ApiURIs {
    
        public static readonly apiURL: string = environment.apiEndpoint;
        public static readonly apiV1: string = environment.apiEndpoint + '/v1';
        public static readonly apiV2: string = environment.apiEndpoint + '/v2';
    
    
        public static readonly login: string = ApiEndpoints.apiV1 + '/login';
        public static readonly register: string = ApiEndpoints.apiV1 + '/register';
        public static readonly signup: string = ApiEndpoints.apiV2 + '/register';
    
    }
    

    Usage of constants

    /core/auth.service.ts

    import { ApiURIs } from './api-constants';
    
    @Injectable()
    export class AuthService {
        .....
    
        signUpUser(data) {
            return this.https.post(`${ApiURIs.signup}`, data);
        }
    
        .....
    }
    

    /auth/login.component.ts

    export class LoginComponent implements OnInit {
       .....
    
       navigateToForgotPassowrd() {
    
            this.router.navigate([Constants.routeAuthRecovery]);
       }
       ......
    }
    

    Define your different API URI's for different environment

提交回复
热议问题