2017-07-25 34 views
0

我需要读入Angular Service Class(TypeScript) - 一个配置文件,其中包含我使用数据的Web服务的基本URL。如何读取Angular 4中的配置参数或文件

它只是一个Ajax调用与HttpClient,但我是新角度。

我服务我的应用程序从Node.js服务器。

此baseUrl更改,这就是为什么它需要进行配置。实际上,我也想检查是否可以将基本Url定义为启动参数。

回答

0

您可以在角度网站阅读非常全面的教程。在这里你可以了解你所需要的所有基本信息:https://angular.io/tutorial/toh-pt6

+0

嗨,你能指点我说他们说配置部分的部分吗?我没有找到它。 –

+0

此外,我使用httpclient,与本教程略有不同 –

0

创建一个名为app.config.ts文件 - 名称可以是你的,象下面这样:

export interface ApplicationConfig { 
    apiURL: string; 
} 

export const CONFIG: ApplicationConfig = { 
    apiURL: 'url to your server'; 
}; 

内为您服务,导入该文件并使用它像这样:

import { CONFIG } from '../config/app.config'; 

@Injectable() 
export class Service { 
    private baseURL: string = CONFIG.apiURL; 

    constructor(private http: Http){} 

    public getSomething():Observable<any> { 
    let url:string = this.baseUrl + 'endpoint url after the base url'; 

    return this.http.get(url).map((res:Response) => res.json()); 
    } 
} 
+0

是否有任何方法可以将URL作为某种参数在启动时传递 –

+0

有一种方法可以做到这一点,结合使用节点进程参数和webpack定义插件。 – cyrix

0

我想说的最简单的例子是做到以下几点:

//Declaring your config 
var myServices = angular.module('some.module', ['ngResource']); 
var myConfingurationService = angular.module('some.module', []); 
    myConfingurationService .constant('CONFIG', { 
     BASE_URL: '/bin/restproxy' 
}); 

//Using your configured parameter 
myServiceFactory.factory('myServices', ['invHttp', 'CONFIG', function (invHttp, CONFIG) { 
    var completeURL = CONFIG.BASE_URL + '/some/other/stuff'; 
} 
0

您可以创建一个基本文件导出您的端点,因此,例如你的base.ts应该是这样的:

export const baseUrl = 'http://yourendpoint.com'; 

这样的话你的组件或服务,你可以使用它像:

import {baseUrl} from './base'; //path to base.ts 
... 
console.log(baseUrl);//http://yourendpoint.com