关于这条链的完成,我想展示val3乘以val5的结果。
现在这是我的模拟服务结构:
{
"person": [{
"val1": 1,
"val2": 2
}],
"facility": [{
"val3": 3,
"val4": 4
}],
"exposure": [{
"val5": 5
}]
}
这是组件,我在其中调用服务。
import { Injectable } from '@angular/core';
import { Person } from './entities/person';
import { HttpClient } from '@angular/common/http';
import { Observable } from '../../node_modules/rxjs/Observable';
@Injectable()
export class DataService {
apiUrl1: string = 'http://localhost:3000/person/?';
apiUrl2: string = 'http://localhost:3000/facility/?';
apiUrl3: string = 'http://localhost:3000/exposure/?';
constructor(private http: HttpClient) {
}
getData(arg): Observable<any> {
return (this.http.get(this.apiUrl1 + arg)
.flatMap((response: any) => this.http.get(this.apiUrl2 + response.val1))
.flatMap((response: any) => this.http.get(this.apiUrl3 + response.val2))
)
}
}
答案 0 :(得分:2)
我想这就是你想要的? (Rxjs使用pipe()方法)。您只需要将值乘以所需的值即可将响应映射为输出。
getData(arg): Observable<any> {
return this.http.get(this.apiUrl1 + arg).pipe(
flatMap((response: any) => this.http.get(this.apiUrl2 + response.val1)),
flatMap((response: any) => this.http.get(this.apiUrl3 + response.val2)),
map((response: any) => response.val3 * response.val5)
)
}
请注意,这只会返回一个数字。因此,如果您还需要其他方式的响应,请订阅它:
constructor(private http: HttpClient) {
this.getData(arg).subscribe(result => {
const output = result.val3 * response.val5;
});
}
getData(arg): Observable<any> {
return this.http.get(this.apiUrl1 + arg).pipe(
flatMap((response: any) => this.http.get(this.apiUrl2 + response.val1)),
flatMap((response: any) => this.http.get(this.apiUrl3 + response.val2))
)
}