Angular 2 – global variable for all components

My angular2 app consuming my backend laravel API in many different components.
I’ve been thinking that in the future, I will need to change the API URL. That means that I will have to change my API URL everywhere (in all components) I have used http get/post method to my API.

Now.. What will be the right way to implement one variable to store the API URL and use it in all of my components?

  1. A service just to set get the API URL
  2. One different service for each of my API objects, for example userAPI.service with user-releated API Calls, peopleAPI.service for people-releatd API Calls, gameAPI.service for game-releated API calls etc..
  3. Anything different that I still don’t know about?

Leave a Reply

2 Comment threads
0 Thread replies
Most reacted comment
Hottest comment thread
1 Comment authors
Jason Recent comment authors
newest oldest most voted
Notify of

You could provide your own request options for this by extending the BaseRequestOptions class. This way the based URL of your Web API will be defined in one place: import {BaseRequestOptions, RequestOptions, RequestOptionsArgs} from 'angular2/http'; export class CustomRequestOptions extends BaseRequestOptions { merge(options?:RequestOptionsArgs):RequestOptions { options.url = '' + options.url; return super.merge(options); } } In the classes that use the Http object, you only need now to use the path and not the whole URL. Here is a sample: this.http.get('/someresource')... You need then to register it when bootstrapping your application. bootstrap(AppComponent, [ HTTP_PROVIDERS, provide(RequestOptions, {useClass: CustomRequestOptions}) ]); See this link for more… Read more »


Bit Confused with extends and all as answer provided by @thierry, you can use one common class/service in which you can store all your global variables and inject that class at the time of bootstrapping by doing so that class is now available to all another classes/components throughout the app and also now you can easily change your variable value by just changing at one place instead of making changes in all components here is example of same – import {Component, Injecable} from 'angular2/core'; import {Http, Response, RequestOptions, Headers, Request, RequestMethod} from 'angular2/http'; @Injecable() export class GlobalService { public base_path:… Read more »