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
Add a comment
|
2 Answers
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/'
}
2 Comments
Scipion
How does that work if that I don't want user 1, but user x ?
Tiberiu Popescu
You will have another setter/method which will update the user. Something like set user(userID) {this.user =
/user/${userID}}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";