【发布时间】:2020-01-13 13:33:20
【问题描述】:
如何在 typescript 中以清晰的方式执行依赖于序列的可观察方法?
示例:
Init(){
this.methodThatUseObservable();
this.methodThatShouldExecuteAfter();
this.anotherMethod();
... (continue)
}
在每个方法中,我都有一个可观察的方法并订阅。
methodThatUseObservable(){
this.service1.get().subscribe(
(value1) => {
this.value1 = value1;
}
)
}
methodThatShouldExecuteAfter(){
this.service2.get(this.value1).subscribe( //depends on the first
(value2) => {
this.value2 = value2;
}
)
}
anotherMethod(){
this.service3.get(this.value2).subscribe( //depends on the second
(value3) => {
this.value3 = value3;
}
)
}
...(so on)
当然可以:
Init(){
this.methodThatUseObservable();
}
在这些方法中的每一个中,其他方法都依赖于:
methodThatUseObservable(){
this.service1.get().subscribe(
(value1) => {
this.value1 = value1;
this.methodThatShouldExecuteAfter();
}
)
}
methodThatShouldExecuteAfter(){
this.service2.get(this.value1).subscribe( //depends on the first
(value2) => {
this.value2 = value2;
this.anotherMethod();
}
)
}
anotherMethod(){
this.service3.get(this.value2).subscribe( //depends on the second
(value3) => {
this.value3 = value3;
...(and so on)
}
)
}
但是我感觉不是很清楚,这样我觉得顺序不是很清楚。
也许解决方案是返回一个承诺并执行 then 方法?
this.methodThatUseObservable().then(()=>{
this.methodThatShouldExecuteAfter();
}).then(()=>{
this.anotherMethod();
})
我不知道这样的结构变化是否可能,请帮忙。
【问题讨论】:
标签: typescript rxjs