将全局常量调用为服务Angular2

时间:2016-06-30 17:53:55

标签: service interface angular constants

在我的Angular2应用程序中,我使用从http://localhost:22222/app/webresources/entity..

调用REST API的服务

我想一次设置此网址的一部分,并从我需要的服务中调用它 我想我需要创建一个具有常量URL的接口,但是可以在服务中实现它吗?

1 个答案:

答案 0 :(得分:1)

我把这样的东西放在我的data-access.service.ts:

export const API_URL: string = "http://my.api.com/"

它非常有用,因为我可以在我的服务方法中使用它:

getStuff(): Observable<Stuff> {
    return this.http.get(API_URL + `/path/to/stuff/with/${parameters}`)
        .map(response => response.json())
        .catch(this.logError);

或稍后在模板中的某个地方:

import { API_URL } from '../shared/data-access.service';

@Component({
    template: '<a href="{{api}}/stuff">Link to stuff</a>'
})
export class MyComponent {
    api: string = API_URL;
…
}
相关问题