简体   繁体   中英

angular2 http response setting to class variable

I am making http call to fetch the data from the local json file. Due to lateness in receive the response, I am not able to display the response data on the template.

Service is making a HTTP call to fetch the data from json file.

export class DataBook {

  bookDetails: Array<Object>;

  constructor(public http: Http) {
      this.bookDetails = [];

  }

  makeDataReady(){
    this.http.get('assets/preloaded-data/booksummaries.json')
                  .map(res => res.json())
                  .subscribe(
                            data => this.bookDetails = data,
                            error => alert(error),
                            () => console.log(this.bookDetails) //output the json file content
                            );
  }

  appendBook(book:Object)
  {
    this.bookDetails.push(book);
  }

  getBooks():Array<Object>
  {
    return this.bookDetails;
  }


}

The below component is making call to initiate the http call.

export class ShowreviewPage {

  items: Object;

  ngOnInit(){
        this.items = this.dataBook.makeDataReady();
  }

  constructor(public navCtrl: NavController, public navParams: NavParams, public dataBook: DataBook) {
        this.items = this.dataBook.getBooks();

      }

  ionViewDidLoad() {
    console.log("ion View did Load",this.items); // empty array output
  }


}

I am new to Angular2. I am struggling to understand why there is a delay in the response?

I found the solution myself. I have just made the http call in the provider or service constructor after this.bookDetails = []; like

constructor(public http: Http) {
    this.bookDetails = [];
    this.init();

}


init(): void {
    this.http.get('assets/preloaded-data/booksummaries.json')
        .map(res => res.json())
        .subscribe(
            data => this.bookDetails = data,
            error => alert(error),
            () => console.log(this.bookDetails) //output the json file content
        );
}

It works fine. Anyway thanks folks!

It's not recommended to put Http calls in the constructor (see this for further information - Difference between Constructor and ngOnInit )

It shouldn't cause any spacial latency if you put it in the ngOnInit or ionViewDidLoad - try it.

Also, in your code sample the constructor appears second (after ngOnInit) - it won't cause error, but it's very non-standard.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM