简体   繁体   中英

Angular two api request and Promise problem

I'm using some ugly api and agly database. And i must to "merge data" from two tables books and authors in angular service in my app. I have in my service two promises:


getBookData() {
    promise = new Promise((resolve, reject) => {
    this.http.get(
      `http://${that.serverAdress}/api/books`,
      that.headers
    ).subscribe((dataBooks: any) => {

// One of data records fields is data.author_id contains raw author id value (api is ugly and i cant fix it)

// All what i need is mix/merge or nesting this two promises for bind (replace) data.author_id to dataAuthor.name  

//exaple record of dataBooks
//0:{name: "Romeo And Julia", aurhor_id = 2}

//i need on output:

//0:{name: "Romeo And Julia", aurhor_id = "William Shakespeare"}

//using this function and getAuthorBy(aurhor_id). This is all my prblem. 

  resolve(dataBooks);
    }, error => {
      reject(error);
    });
  });
  return promise;
}


//and other promise returns author data  (specified by id)


getAuthorBy(id) {
  promise = new Promise((resolve, reject) => {
    this.http.get(
      `http://${that.serverAdress}/api/authors/${id}`,
      that.headers
    ).subscribe((dataAuthor: any) => {



     resolve(dataAuthor);
    }, error => {
      reject(error);
    });
  });
  return promise;
}

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc eget nulla feugiat, vehicula massa at, maximus eros. Praesent tincidunt magna quis ante hendrerit, nec bibendum eros placerat. Vivamus at finibus quam because "It looks like your post is mostly code; please add some more details."

If I understand the task correctly you can use forkJoin() to get data at once from several requests.

forkJoin(observable1$, observable2$).subscribe(([observable1, observable2]) => {
    // work with the observables
});

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