无法在Angular2中读取配置文件

时间:2016-11-25 08:48:12

标签: angular configuration-files

下面是我的代码,我试图从JSON配置文件中读取值。但是当我调用方法getApiURL时,它返回一个空字符串。无法理解这里出了什么问题...

import { Injectable } from '@angular/core';
import { Http, Response, Headers } from '@angular/http';
import { Observable } from 'rxjs/Rx';

@Injectable()
export class WebApiConfiguration {
    public apiURL: string = "";

    constructor(private _http: Http) {
    }
    public load() {
        return new Promise((resolve, reject) => {
            this._http.get('/Utils/LSConfig.json')  
                .map(res => res.json())
                .subscribe(
                (data: any) => {
                    this.apiURL = data.WebAPIUrl;
                    resolve(true);
                },
                err => console.log(err)
                );
        });
    }


    public getApiURL = (): string => {
        return this.apiURL;
    }
}

这个配置类作为可注入的方式传递给调用构造函数类,如下所示:

@Injectable()
export class LSService implements ILSService {

    private actionUrl: string;
    private headers: Headers;

    constructor(private _http: Http, private _configuration: WebApiConfiguration      ) {
        this.actionUrl = _configuration.getApiURL();
        this.headers = new Headers();
        this.headers.append('Content-Type', 'application/json');
    }

我的配置LSConfig.json文件很简单,如下所示,只包含一个值:

{
  "WebAPIUrl": "http://localhost/WebAPI/"
}

现在,每次_configuration.getApiURL()都会返回一个空字符串。不知道什么是错的......任何想法?

0 个答案:

没有答案