How to make a string constant in angular 4? How to make a string constant in angular 4? angular angular

How to make a string constant in angular 4?


I'm not sure if i understand your question but if you want to create constants, you can do it in a different class and import it.

constants.ts

export class Constants {  public static get HOME_URL(): string { return "sample/url/"; };}

sample.component.ts

   import { Constants } from "./constants";    @Component({    })     export class SampleComponent {      constructor() {       let url = Constants.HOME_URL;      }    }


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


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

environments file & .angular-cli.json