如何正确加载我的angular2应用程序的设置

时间:2016-08-06 11:34:49

标签: typescript angular rxjs5

我正在尝试进行初始化设置,但似乎我做错了

main.service.provider.ts

import {Injectable} from "@angular/core";
import {Http, Response} from '@angular/http';
import {Observable}     from 'rxjs/Observable';
import "../lib/lib";
@Injectable()
export class MainServiceProvider {
  private _settings: any;
  private _error: boolean;

  constructor(private http: Http) {
    this._error = false;
//try load settings here
    this._getsettings().subscribe(
      resp => {
        console.log(resp);
        this._settings = resp
      },
      error => {
        console.error(error);
        this._error = true;
      }
    );
  }


  //main request to server function
  public getData(citieslist: Array<string>): Observable<Object> {
    if ((typeof  citieslist === 'object') && (citieslist.length > 0)) {
      let adressarray: Array<any> = [];
      for (let city of citieslist) {
        let url = this._settings.url + this._settings.searchparam + city;
        adressarray.push(this.http.get(url).map((res: Response) => this._extractData(res)).catch(this._handleError))
      }
      return Observable.forkJoin(adressarray)
    }
    else
      console.error('no valid data in function parameter');
  }
  //data handler
  private _extractData(res: Response) {

    let body = res.json();
    return body || {};
  }
  //error handler function
  private _handleError(error: any) {

    let errMessage = (error.message) ? error.message :
      error.status ? `${error.status} - ${error.statusText}` : 'server error';
    console.error(errMessage);
    return Observable.throw(errMessage);
  }
  //settings getter
  public _getsettings(): Observable<Object> {
    return this.http.get('/data/settings.json').map((res: Response) => this._extractData(res)).catch(this._handleError);
  }
}

在app.component中我订阅了ngOnInit中的GetData函数 结果:当我启动应用程序时,GetData首先执行,而不是在main.service.provider中看到设置

0 个答案:

没有答案