【问题标题】:Angular 2 - global variable for all componentsAngular 2 - 所有组件的全局变量
【发布时间】:2016-08-08 06:08:27
【问题描述】:

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

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

  1. 仅用于设置获取 API URL 的服务
  2. 我的每个 API 对象都有一个不同的服务,例如带有用户相关 API 调用的 userAPI.service、用于人员相关 API 调用的 peopleAPI.service、用于游戏相关 API 调用的 gameAPI.service 等等。
  3. 还有什么我不知道的不同之处?

【问题讨论】:

    标签: angular


    【解决方案1】:

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

    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。这是一个示例:

    this.http.get('/someresource')...
    

    然后您需要在引导您的应用程序时注册它。

    bootstrap(AppComponent, [
      HTTP_PROVIDERS,
      provide(RequestOptions, {useClass: CustomRequestOptions})
    ]);
    

    查看此链接了解更多详情:

    【讨论】:

    • 太棒了!但是当我在boot.ts 中使用provide 时,出现以下错误:Error: ReferenceError: provide is not defined。就是这样:import {CustomRequestOptions} from "./helpers/CustomRequestOptions"; bootstrap(AppComponent, [ JwtService, HTTP_PROVIDERS, ROUTER_PROVIDERS, MATERIAL_PROVIDERS, SidenavService, provide(RequestOptions, {useClass: CustomRequestOptions}) ]);
    • 是的,你需要从“angular2/core”模块中导入“provide”功能...
    • 这很好,只是要注意它不适用于 http.post* 和 **http.put ,但它适用于 http。 request ,所以你可以有类似的东西:this.http.request('/user/1', { body: body, method: 'PUT' })
    【解决方案2】:

    Bit 混淆extends 以及@thierry 提供的所有答案,您可以使用一个通用类/服务,您可以在其中存储所有全局变量并在引导时注入该类,这样该类是现在可用于整个应用程序中的所有其他类/组件,现在您可以通过在一个地方更改而不是在所有组件中进行更改来轻松更改变量值这里是相同的示例 -

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

    然后像这样在引导程序中注册这个服务类 -

    bootstrap(AppComponent, [
      HTTP_PROVIDERS,GlobalService , XYZ...
    ]);
    

    现在这个GlobalService 类可供所有其他类使用,

    现在也不需要在每次使用时在提供者列表中注册此类,因为 Angular 本身会将其初始化为所有组件,现在在任何此类中使用这些全局变量/函数 -

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-05-16
      • 2016-07-16
      • 1970-01-01
      • 1970-01-01
      • 2017-02-05
      • 1970-01-01
      • 2022-01-25
      相关资源
      最近更新 更多