简体   繁体   English

angular6 中的串行 api 调用

[英]Serial api call in angular6

I have parent component with two child component.我有两个子组件的父组件。 Every off child components have OnInit api call with some date that will show in that components.每个关闭的子组件都有 OnInit api 调用,其中包含将显示在该组件中的某个日期。

Can I call this api's serially?我可以连续调用这个api吗? So first load api 1 and thent api 2?那么首先加载api 1然后加载api 2?

Use Concat使用连接

Concat will combine two observables into a combined sequence, but the second observable will not start emitting until the first one has completed. Concat 会将两个 observable 组合成一个组合序列,但第二个 observable 在第一个完成之前不会开始发射。

let first = Observable.timer(10,500).map(r => {
  return {source:1,value:r};
}).take(4);
let second = Observable.timer(10,500).map(r => {
  return {source:2,value:r};
}).take(4);
first.concat(second).subscribe(res => this.concatStream.push(res));

Ref: http://www.syntaxsuccess.com/viewarticle/combining-multiple-rxjs-streams-in-angular-2.0参考: http : //www.syntaxsuccess.com/viewarticle/combining-multiple-rxjs-streams-in-angular-2.0

This can be achieved using ForkJoin, which will allow Http call trigged async and parallel.这可以使用 ForkJoin 来实现,这将允许 Http 调用触发异步和并行。 Here is the Code这是代码

const apiCalls = [
   service.method1(),
   service.method2(),
];

return forkJoin(apiCalls).map((results)=>{
    console.log(results);
    return results;
});

Note: both method1() & method2() will return Observable.注意:method1() 和 method2() 都会返回 Observable。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM