简体   繁体   English

配置Angular 2 HTTP服务

[英]Configure Angular 2 HTTP service

I wonder what is the right way to use http service. 我想知道使用http服务的正确方法是什么。 For example all my requests to server starts with /Api . 例如,我对服务器的所有请求都以/Api开头。 Should I write this.http.get('/Api/SomeRoute/:id') every time, or more elegant way exists to omit Api ? 我应该this.http.get('/Api/SomeRoute/:id')this.http.get('/Api/SomeRoute/:id') ,还是更优雅的方式来省略Api

Or should I create some other managerService which will use http ? 或者我应该创建一些其他将使用http managerService

Something like an endpoint url is probably a good example for a general configuration file. 端点URL这样的东西可能是一般配置文件的一个很好的例子。

In my angular 2 apps i use the dependency injection for it. 在我的角度2应用程序中,我使用依赖注入。 In this case i have something like an app.config.ts using OpaqueToken to make it injectable: 在这种情况下,我有一个类似于app.config.ts使用OpaqueToken使其可注入:

import { OpaqueToken } from '@angular/core';

export interface IAppConfig {
    appTitle: string;
    endpointUrl: string;
};

export const CONFIG: IAppConfig = {
    appTitle: 'MyApp',
    endpointUrl: 'http://api.myrealservice.com/'
};

export const LOCALCONFIG: IAppConfig = {
    appTitle: 'MyApp (LOCAL)',
    endpointUrl: 'http://localhost:8080/api/'
};

export let APP_CONFIG = new OpaqueToken('app.config');

This way you can have several configs (for example for local development or production etc..) and define this as a provider in your module like this: 通过这种方式,您可以拥有多个配置(例如,用于本地开发或生产等),并将其定义为模块中的提供程序,如下所示:

providers: [
    ...,
    {
        provide: APP_CONFIG,
        useValue: CONFIG
    },
    ...
]

Then i just inject this config wherever i may need it, for example in a backend service to use the endpointUrl : 然后我只是在需要它的地方注入此配置,例如在后端服务中使用endpointUrl

...
constructor(@Inject(APP_CONFIG) private _config:Config) {
    console.log(this._config.endpointUrl);
}

In your module you can just change the kind of Config you want to provide (in this example CONFIG or LOCALCONFIG for example) and don't have to change it anywhere else anymore. 在您的模块中,您只需更改要提供的配置类型(例如,在此示例中为CONFIGLOCALCONFIG ),而不必在其他任何地方更改它。

Hope this helps. 希望这可以帮助。


After your edit, you added a second question Or should I create some other managerService which will use http? 编辑后,你添加了第二个问题或者我应该创建一些其他将使用http的managerService? :

Short answer: yes. 简短回答:是的。 You should seperate logic of your components, services, etc. as much as possible. 您应该尽可能地分离组件,服务等的逻辑。

Let's say you have a an API which serves information about cats and dogs. 假设您有一个API,提供有关猫和狗的信息。 What you want to have in your frontend would probably be a CatService , a DogService and a BackendService or ApiService , whatever you want to call it. 您希望在前端拥有的内容可能是CatServiceDogServiceBackendServiceApiService ,无论您想要什么称呼它。

The CatService and DogService are the ones your view components will interact with, for example they will have methods like getCatById() or something like that. CatServiceDogService是您的视图组件将与之交互的组件,例如,它们将具有getCatById()类的方法。 These services will most likely interact with anohter service, the BackendService which will inject Http and use general methods like post() , get() and so on. 这些服务将最有可能与anohter服务进行交互时, BackendService将注入Http和使用像一般方法post() get()等。

So your BackendService is the one who has to know the specific urls, handle the responses or errors and report back to the calling services with the results, while the other ones will just be used as a pipeline and handle specific business logic. 因此,您的BackendService必须知道特定的URL,处理响应或错误并使用结果向调用服务报告,而其他的只是用作管道并处理特定的业务逻辑。

You are right, it is better to put repeating values in a variable. 你是对的,最好在变量中加入重复值。 You can put the base URL in a const : 您可以将基本URL放在const

const apiUrl = '/Api/';

and then if there is a change to the URL, you only change it in one place, and also your code looks cleaner. 然后,如果URL有变化,您只能在一个地方更改它,而且您的代码看起来更干净。 The usage is like this: 用法是这样的:

this.http.get(apiUrl + 'SomeRoute/:id')

Of course you can also create a function that does that for you, but that may be too much abstraction. 当然你也可以创建一个为你做这个的功能,但这可能是太过抽象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM