下面是我的代码,我试图从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()
都会返回一个空字符串。不知道什么是错的......任何想法?