How to make string constant in angular 4?

In my service I use a message http. I want to set the URL as a constant.

return this.http.get(this.config.API_URL+'users', options).map(res=>res.json());

I tried with the service:

import {Injectable} from '@angular/core';

@Injectable()
export class AppService {
  API_URL :String;

  constructor() {
    this.API_URL = 'some url';
  }
}

Is there any other way to make a constant value in Angular4?

+13
source share
3 answers

I'm not sure if I understand your question, but if you want to create constants, you can do it in another 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;
      }
    }
+33
source

You can simply export the constant using es6 / typescript modules if that is all you need:

constants.ts:

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

And import where necessary:

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());

, . : angular2 .

+31

,

public static readonly constName = ' Consts'

/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

URI . .angular-cli.json. .

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';

}

/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 other API URI for a different environment

environments file & .angular-cli.json

+1
source

Source: https://habr.com/ru/post/1017172/


All Articles