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?
We always need to declare global variable file for our angular 10 application because we can set some global variable there like site title, api url etc so you can easily access any where in our application easily. So, in this example, we will create GlobalConstants file for adding global variables in our application.
AngularJS expressions do not have direct access to global variables like window , document or location .
tSetGlobalVar allows you to define and set global variables in GUI. For more technologies supported by Talend, see Talend components.
The clean, reliable way to declare and define global variables is to use a header file to contain an extern declaration of the variable. The header is included by the one source file that defines the variable and by all the source files that reference the variable.
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 = 'http://10.7.18.21:8080/api' + 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 details:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With