小编Jon*_*onH的帖子

如何在angular2中预加载配置文件

我正在帮助使用webpack开发angular2 web应用程序,我们当前的计划是打开某种文件来配置我们的应用程序的功能(可能是.json).这主要是为了让人们实现我们的应用程序一个易于定位的文件,以指定以下内容:他们的API位于何处,是否要添加自定义样式表等.

我用来加载配置文件的服务如下所示:

//config.ts
@Injectable()
export class Config {
    private static _config: Object;
    private static _promise: Promise<any>;

    constructor(private http: Http) {
        Config._promise = this.load();
    }

    load() {
        return new Promise((resolve, reject) => {
            this.http.get(`./config/development.json`)
                .map((response: Response) => response.json())
                .catch((error: any) => {
                    console.error(error);
                    return Observable.throw(error.json().error || 'Server error');
                })
                .subscribe((data) => {
                    Config._config = data;
                    resolve(true);
                });
        });
    }

    get(key: any) {
        return  Config._config[key];
    }
}
Run Code Online (Sandbox Code Playgroud)

我在另一个服务类中使用它:

//api.service.ts
@Injectable()
export class ApiService {
    private URI: string;

    constructor(private http: Http, private …
Run Code Online (Sandbox Code Playgroud)

configuration config preload typescript angular

6
推荐指数
1
解决办法
2347
查看次数

标签 统计

angular ×1

config ×1

configuration ×1

preload ×1

typescript ×1