简体   繁体   English

Angular两个api请求和Promise问题

[英]Angular two api request and Promise problem

I'm using some ugly api and agly database.我正在使用一些丑陋的 api 和 agly 数据库。 And i must to "merge data" from two tables books and authors in angular service in my app.而且我必须在我的应用程序的 angular 服务中“合并数据”来自两个表格书籍和作者。 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. Lorem ipsum dolor sit amet, consectetur adipiscing elit。 Nunc eget nulla feugiat, vehicula massa at, maximus eros. Nunc eget nulla feugiat, vehicula massa at, maximus eros。 Praesent tincidunt magna quis ante hendrerit, nec bibendum eros placerat. Praesent tincidunt magna quis ante heendrerit, nec bibendum eros placerat。 Vivamus at finibus quam because "It looks like your post is mostly code; please add some more details." Vivamus 在 finibus quam 因为“看起来你的帖子主要是代码;请添加更多细节。”

If I understand the task correctly you can use forkJoin() to get data at once from several requests.如果我正确理解任务,您可以使用forkJoin()从多个请求中一次获取数据。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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