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: string;
public headers: Headers;
public requestoptions: RequestOptions;
public res: Response;
constructor(public http: Http, public router: Router) {
this.base_path = "http://128.199.190.109/api/";
}
public getRequsetOptions(url: string): RequestOptions {
this.headers = new Headers();
this.headers.append("Content-type", "application/json");
this.headers.append("Authorization", 'Bearer ' + localStorage.getItem('id_token'));
this.requestoptions = new RequestOptions({
method: RequestMethod.Get,
url: url,
headers: this.headers
});
return this.requestoptions;
}
}
and just register this service class in bootstrap like this -
bootstrap(AppComponent, [
HTTP_PROVIDERS,GlobalService , XYZ...
]);
Now this GlobalService
class is available to all another classes,
also now no need to register this class in the list of providers every time when you use because angular itself initialize this to all components, Now use these global variables/function in any class like this -
import {GlobalService} from './GlobalService';
import {Http} from 'angular2/http';
@Injectable()
export class ABC {
constructor(private base_path_service: GlobalService, private http: Http) {}
SomeMethod(url) {
return this.http.request(new Request(this.base_path_service.getRequsetOptions(url)))
.map(res=> {
// DO your code
});
}