我正在使用一些后端服务来使用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****/*****');
}
}
您似乎需要同时获得两个服务的响应;如果是这样的话,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分组到一个可观察数组中,最后返回该可观察数组。你可以使用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
});
}
一种解决方案是使用RxJs combineLatest运算符来组合所有服务的响应:
submit() {
combineLatest(
this.service1.getData(),
this.service2.getData(),
this.service3.getData()
).subscribe(allData => ...)
}
编辑:进一步思考,我建议对于这个用例,每个HTTP请求应该完成,你使用forkJoin
作为Tushar Walzade的回答。 This SO answer简要解释了forkJoin
和combineLatest
之间的区别。