2017-07-25 517 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