简体   繁体   中英

angular 6,how to merge responses from a api into a single array

here i got two Json responses ie., books and authors.i want those two responses in a single array

this.http.getbooks().subscribe(
    data=>{
    this.getbooksinfo=data;
    }
)
this.http.getauthors().subscribe(
    data=>{
    this.authors=data;
    }

)

getauthors,getbooks info are two methods that gets info from restapi using http get method..how to store this.author and this.booksinfo in single array?

You can optionally use forkJoin :

const books = this.http.getbooks();
const authors = this.http.getauthors();

forkJoin([books, authors]).subscribe(response => {
 // response[0] will be req1 response
 // response[1] will be req2 response
})

The other option as mentioned in the comments is using combineLatest :

combineLatest(books, authors).subscribe(response => {
 ...
})

I don't know if my answer will suit you but, you can create an empty array object in your component and when you do the RESTAPI call you just do a push on the object.

Something like:

private arrayObject: any = [];

this.http.getbooks().subscribe(
    data=>{
    this.getbooksinfo=data;
    this.arrayObject.push(this.getbooksinfo);
    }
)
this.http.getauthors().subscribe(
    data=>{
    this.authors=data;
    this.arrayObject.push(this.authors);
    }

)

EDITED ---

Following edkeveked comment, you can user forkJoin, but need to change a little bit your code.

import { forkJoin } from "rxjs/observable/forkJoin";
    let apibooks = this.httpClient.get('YOU_API_URL');
    let apiauthors = this.httpClient.get('YOU_API_URL');

    forkJoin([apibooks, apiauthors]).subscribe(results => { console.log(results); // will print array of results;
console.log(results[0]); // will print apibooks results;
console.log(results[1]); // will print apiauthors results;
});

Print to console log so you can understand whats happening.

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