简体   繁体   English

如何合并多个REST API JSON output并显示在MatTable Angular

[英]How to combine multiple REST API JSON output and show in MatTable Angular

I'm calling four different REST endpoints, I want to combine all these results into single JSON and show in the Angular Mat table.我正在调用四个不同的 REST 端点,我想将所有这些结果组合成一个 JSON 并显示在 Angular Mat 表中。 I tried pushing into an array but its creating nested JSON object and not showing anything in table.我尝试推入一个数组,但它创建了嵌套的 JSON object 并且没有在表中显示任何内容。 Please find my code below:请在下面找到我的代码:

post.component.ts后.component.ts

import { Component, OnInit, ViewChild, ChangeDetectorRef } from '@angular/core';
import { animate, state, style, transition, trigger } from '@angular/animations';
import { MatTableDataSource } from '@angular/material/table';
import { MatPaginator } from '@angular/material/paginator';
import { MatSort, Sort } from '@angular/material/sort';
import { LiveAnnouncer } from '@angular/cdk/a11y';
import { PostService } from './post-service';
import { Post } from './post';

export class PostComponent implements OnInit {


    @ViewChild(MatPaginator) paginator: MatPaginator;
    @ViewChild(MatSort) sort: MatSort;

    post: Post[];
    dataSource;
    columnsToDisplay = ['postId', 'id', 'name', 'email', 'body'];
    my_array = [];

    /**
     * Constructor
     */
    constructor(
        private postService: PostService,
        private _liveAnnouncer: LiveAnnouncer,
        private cdr: ChangeDetectorRef) { }

    listPost() {
        this.onGetPost('post-1');
        this.onGetPost('post-2');
        this.onGetPost('post-3');
        this.onGetPost('post-4');
    }

    onGetPost(postId): void {
        this.postService.getPost(postId).subscribe(
            (response) => {
                console.log(response);
                this.my_array.push(response);
                this.post = this.my_array;
                this.dataSource = new MatTableDataSource(this.post);
                this.cdr.detectChanges();
                this.dataSource.paginator = this.paginator;
                this.dataSource.sort = this.sort;
            },
            (error: any) => {
                console.log('entering into error block')
                console.log(error)
                this.dataSource = new MatTableDataSource();
                this.cdr.detectChanges();
                this.dataSource.paginator = this.paginator;
                this.dataSource.sort = this.sort;

            },
            () => console.log('Done getting all post')
        );
    }

    filterData($event: any) {
        this.dataSource.filter = $event.target.value;
    }
    announceSortChange(sortState: Sort) {
        if (sortState.direction) {
            this._liveAnnouncer.announce(`Sorted ${sortState.direction}ending`);
        } else {
            this._liveAnnouncer.announce('Sorting cleared');
        }
    }

    /**
     * On init
     */
    ngOnInit(): void {
        this.listPost();

    }

}

post-service.ts服务后.ts

import { Injectable } from "@angular/core";
import { HttpClient } from "@angular/common/http";
import { Observable } from "rxjs";
import { Post } from "./post";

@Injectable({ providedIn: 'root' })
export class PostService {

    constructor(private http: HttpClient) { }
    endpoint: any;
    getPost(id): Observable<Post[]> {

        console.log(id);
        switch (id) {
            case 'post-1':
                this.endpoint = 'https://jsonplaceholder.typicode.com/posts/1/comments';
                break;
            case 'post-2':
                this.endpoint = 'https://jsonplaceholder.typicode.com/posts/2/comments';
                break;
            case 'post-3':
                this.endpoint = 'https://jsonplaceholder.typicode.com/posts/3/comments';
                break;
            case 'post-4':
                this.endpoint = 'https://jsonplaceholder.typicode.com/posts/4/comments';
                break;
        }
        return this.http.get<Post[]>(this.endpoint);
    }
}

Could you please help me to resolve this issue.你能帮我解决这个问题吗? Appreciated your support on this.感谢您对此的支持。 Thanks!谢谢!

you can use RxJs and use pipe and switchMap, then in every switch map try to concat results of API's您可以使用 RxJs 并使用 pipe 和 switchMap,然后在每个开关 map 中尝试连接 API 的结果
swithcMap refrence swithcMap参考

another way is using forkJoin, first change result of onGetPost to observable and then you code can be like this:另一种方法是使用 forkJoin,首先将 onGetPost 的结果更改为可观察的,然后你的代码可以是这样的:

let fk = [];
fk.push(onGetPost('x'));
fk.push(onGetPost('y'));
fk.push(onGetPost('z'));

after that之后

forkJoin(fk).subscribe(a=> { code to concat result})

concat result of the forkJoin forkJoin 的连接结果

forkJoin refrence forkJoin 参考

with fork join you can get onGetPost with different id's dynamically使用 fork join,您可以动态地获得具有不同 ID 的 onGetPost

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

相关问题 如何从 rest-api 在 Angular 中的图像上显示加载指示器 - How to show loading indicator on images in Angular from rest-api 如何从 JSON REST-API 在 jQuery 中显示特定变量? - How to show specific variable in jQuery from JSON REST-API? Angular 8:如何从 json REST API 创建枚举 - Angular 8: How to create enum from json REST API Angular2如何从Yahoo Finace Rest API获取JSON格式 - Angular2 How to get json form Yahoo Finace rest api 如何在角度数据表中组合数据并显示图像 - How to combine data and show image in angular datatable Angular 如何结合Interval和Zip显示loading - Angular How to combine Interval with Zip to show loading Angular - How to get posts, tags and comment count from Wordpress REST API using switchMap and then combine the resulting values using JavaScript? - Angular - How to get posts, tags and comment count from Wordpress REST API using switchMap and then combine the resulting values using JavaScript? 对于 Angular Material MatTable,当多个查询链接时,AngularFire 集合查询“this.filteredData”未定义 - For Angular Material MatTable, AngularFire collection query "this.filteredData" is undefined when multiple queries are chained 如何在JSON对象中组合多个键值? - How to combine multiple key values in JSON object? 使用从REST API返回的JSON数组以角度表? - Using json array returned from rest api in angular for a table?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM