0

I'm trying to do the initialization settings, but it seems that I am doing something wrong

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);
  }
}

In app.component i subscribing on GetData function in ngOnInit As result: when i start app, GetData execute first and not seen settings in main.service.provider

slowkazak
  • 95
  • 1
  • 4
  • Please show the code how you invoke the method on the service and where the problem happens. – Günter Zöchbauer Aug 06 '16 at 11:37
  • Sorry, only this way my provider fail dns and plunkr, jsfiddle and other not working https://bitbucket.org/slowkazak/weather_spa/get/fd6fa28c6fb8.zip – slowkazak Aug 06 '16 at 11:45
  • Please add the relevant code to your question. I don't intend to download files to my local disk. – Günter Zöchbauer Aug 06 '16 at 11:46
  • http://plnkr.co/edit/73g6eH47bjeST8mlPTYo?p=preview – slowkazak Aug 06 '16 at 12:24
  • If you fetch data async you can't expect the data to have arrived without properly chaining the calls. http://stackoverflow.com/questions/36271899/what-is-the-correct-way-to-share-the-result-of-an-angular-2-http-network-call-in might help in your case. – Günter Zöchbauer Aug 06 '16 at 12:31

0 Answers0