0

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

2 Answers 2

1

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/'
}
Sign up to request clarification or add additional context in comments.

2 Comments

How does that work if that I don't want user 1, but user x ?
You will have another setter/method which will update the user. Something like set user(userID) {this.user = /user/${userID}}
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.