使用多个服务来填充Angular Data-Table

问题描述 投票:0回答:3

我正在使用一些后端服务来使用Material Designs数据表填充三个列。我正在使用一个observable来填充数据源数据。但是如何包含其他服务的数据。到目前为止,我只能使用来自一个服务的数据。我的思考过程是使用.push来处理数据。

dataSource = []

constructor(public data: xService, public otherData: yService) { }

submit() {
    this.data.getUsers().subscribe(data => {
        this.dataSource = data.rows;
    });

    this.otherData.getUnitAssignments().subscribe(otherData => {
        this.dataSource.push({ assignments: otherData });
    });
}

服务文件

export interface xresponse {
  rows: Array < string > ,
}
constructor(private http: HttpClient) {}

getUsers(): Observable<xResponse> {
  return this.http.get<xResponse>('/services/****/user/j**/******');
}

其他服务

export interface yResponse {
    rows: Array<string> ,
}

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

    constructor(private http: HttpClient) {}

    getyInfo(): Observable<yResponse> {
        return this.http.get<yResponse>('/services/c***/user/j****/*****');
    }
}
angular http datatable angular-material observable
3个回答
2
投票

您似乎需要同时获得两个服务的响应;如果是这样的话,RxJS ForkJoin就是你的朋友!您可以使用forkJoin如下 -

import { forkJoin } from 'rxjs';

submit() {
    const combined = forkJoin([
        this.data.getUsers(),
        this.otherData.getUnitAssignments()
    ]);
    combined.subscribe((response) => {
        // you will get 2 arrays in response
        this.dataSource.push(response[0].rows);
        this.dataSource.push(response[1].rows);
    });
}
  • 仅供参考,forkJoin等待每个http请求完成,并将每个http调用返回的所有observable分组到一个可观察数组中,最后返回该可观察数组。

1
投票

你可以使用RxJs forkJoin运算符。这样,只有在收到所有回复时才会构建你的dataSource(正如官方文档中说的那样,它与Promise.all类似):

ngOnInit(): void {
    forkJoin([this.data.getUsers(), this.otherData.getUnitAssignments()])
        .subscribe(result => {
            this.firstRequestResult = result[0];
            this.secondRequestResult = result[1];
            //building your dataSource here

        });
}

1
投票

一种解决方案是使用RxJs combineLatest运算符来组合所有服务的响应:

submit() {
  combineLatest(
    this.service1.getData(),
    this.service2.getData(),
    this.service3.getData()
  ).subscribe(allData => ...)
}

编辑:进一步思考,我建议对于这个用例,每个HTTP请求应该完成,你使用forkJoin作为Tushar Walzade的回答。 This SO answer简要解释了forkJoincombineLatest之间的区别。

© www.soinside.com 2019 - 2024. All rights reserved.