简体   繁体   中英

Late response from API

I am learning TypeScript and currently I am trying to use google API for books. Issue that I have, is that at the time when expect to get get a response I have null. However, I am logging response and data is presented console. Next strange this that, this data is logged and the end of all my code (like the last thing, but not when I am actually doing logging method). Is there a way to wait for response? My code parts:

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { OrderPage } from '../order/order';
import { BooksApiProvider } from '../../providers/books-api/books-api';

@Component({
  selector: 'page-book',
  templateUrl: 'book.html'
})
export class BookPage {

    books:any;

    constructor(public navCtrl: NavController, public booksProvide: BooksApiProvider) {
    }

  moveToOrder() {
    debugger;
    this.books = this.booksProvide.getBook();
  }
}
import { Injectable } from '@angular/core';
import 'rxjs/add/operator/map';


@Injectable()
export class BooksApiProvider {

  constructor() {
  }

  getBook(){
    fetch('https://www.googleapis.com/books/v1/volumes?q=isbn:9780439139601')
    .then(res => res.json())
    .then(data => console.log(data))
  }
}

Your getBook() method doesn't return anything, therefore, this.books will always be null.
As you're using fetch here, you can return the promise in your getBook() method allowing you to perform any action with the data retrieved.

getBook(): Promise<any> {
  return fetch('https://www.googleapis.com/books/v1/volumes?q=isbn:9780439139601')
    .then(res => res.json())
    .then(data => {
      console.log(data);
      return Promise.resolve(data);
    });
}

Then you can call .then on getBook() to do whatever you want with the data.
(Assign the data to this.books for example)

this.booksProvide.getBook()
  .then(data => this.books = data);

You're using Angular thought, you should take a look at the HttpClient . It's pretty much the same as fetch unless it deals with RxJS and Observables which are widely used in Angular.

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