Angular 2-所有组件的全局变量 [英] Angular 2 - global variable for all components

查看:159
本文介绍了Angular 2-所有组件的全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的angular2应用程序在许多不同的组件中使用了后端laravel API. 我一直在想,将来我将需要更改API URL.这意味着我将不得不在已对我的API使用http get/post方法的所有地方(所有组件中)更改API URL.

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.

现在..实现一个变量来存储API URL并将其用于我所有组件的正确方法是什么?

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. 仅用于获取API URL的服务
  2. 我的每个API对象都有一个不同的服务,例如,带有用户相关API调用的userAPI.service,用于与用户相关的API调用的peopleAPI.service,用于与游戏相关的API调用的gameAPI.service等.
  3. 我仍然不知道有什么不同吗?

推荐答案

您可以通过扩展BaseRequestOptions类来为此提供自己的请求选项.这样,将在一个位置定义Web API的基于URL:

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);
  }

}

在使用Http对象的类中,您现在只需要使用路径而不是整个URL.这是一个示例:

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:

这篇关于Angular 2-所有组件的全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆