Scipion
Scipion

Reputation: 11888

Define an API endpoint in Angular2 (typescript)

I am very new in Angular2. I would like to have a single class having all my API endpoints (allowing parameters and such in the different routes) that I could inject in all my services. What's the best way to do so in Angular2. I mean, should I define an @Injectable class as you would do when defining a service (and then add it to my services'PROVIDERS) or is it something similar to constant in angular 1.x that I could use

Upvotes: 0

Views: 3068

Answers (2)

Madhu Ranjan
Madhu Ranjan

Reputation: 17934

you may try directly adding a constant file which exports all your constant if that solves your purpose,

constants.ts

    export var APPCONSTANTS: any = {
       GETDATA_API_PATH  : "some path here"
    }

If you want intellisense you will have to define a interface which will list all possible properties like below and give the type of APPCONSTANTS as IAppConstant,

  interface IAppConstant{
      GETDATA_API_PATH: string
  }

import constant and use,

   import { APPCONSTANTS } from "./constants"; // give relative path
   ...
   ...
   let x = APPCONSTANTS["GETDATA_API_PATH"];
   or 
   let x = APPCONSTANTS.GETDATA_API_PATH";

Upvotes: 0

Tiberiu Popescu
Tiberiu Popescu

Reputation: 4524

I would create an @Injectable Class, so you can compose the API if you need so.
I have an API service which is injected in the bootstrap(app singleton) and it's used in all other services, this is how it looks like :

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

@Injectable()
export class ApiService {
    // Hardcoded user :
    private user: string = '/user/1';

    get userCars() {
        return `${this.user}${API.userCars}`
    }

    get userRegisterCar() {
        return `${this.user}${API.userRegisterCar}`
    }

    get profile() {
        return this.user;
    }
}

const API = {
    userCars: '/usercar/details=true',
    userRegisterCar: '/usercar/registration/'
}

Upvotes: 1

Related Questions