【发布时间】:2018-03-14 13:59:37
【问题描述】:
我为我的 Angular 应用程序创建了一个自定义 loaderService,它在后端处理请求(或一组请求)时提供加载微调器。这是我的代码:
export class ComponentOne {
constructor(loaderService: LoaderService, orderService: OrderService) {}
...
...
method() {
this.loaderService.display(true);
this.orderService.firstRequest()
// the misspelled word causes a 500 error
.then((response) => this.orderService.methodWithWrongInput('misspelled_word'))
// but it still executes the following then
.then(() => this.method2())
.catch(() => null)
.then(() => this.loaderService.display(false));
}
...
}
我在请求之前显示微调器,但无论请求成功还是失败,我都想确保关闭它。这就是为什么我在底部放一个catch 和最后一个then。代码运行良好,但是当我调试它时,我意识到即使第二个请求(故意拼错的单词)失败,method2() 仍然被调用。还是真的失败了?
我的问题是,catch 方法在链接请求时如何工作。我以为如果请求失败,我们直接去 catch 方法,但我可能错了。
编辑: 原来我对 method2() 的调用是错误的。见 T.J.克劳德的回答更多。
【问题讨论】:
-
隐藏
.finally()块中的微调器。 -
"...我意识到即使第二个请求(故意拼错单词)失败,method2() 仍然被调用。" 不,它肯定会如果
methodWithWrongInput抛出或返回最终拒绝的承诺,则不是。 (请注意,显示的代码缺少)。)不会调用包含method2的then处理程序;后面的catch会是。 -
@Sajal:标准承诺没有
.finally(目前)。这个.catch(...).then(...)成语是在没有人的情况下处理finally 情况的经典方法。 -
@T.J.Crowder 嗯,那我可能错了……那是不是意味着一旦请求失败,
catch方法就会被调用? -
@T.J.Crowder,明白了。我通常使用
rxjs/Observable,它有finally块。
标签: angular http typescript promise