Ste*_*nie 47 http subscribe angular
我觉得这个场景应该在Angular 2文档中,但我无法在任何地方找到它.
这是场景
我想它的工作方式如下:
this.projectService.create(project)
.subscribe(
result => console.log(result),
error => {
this.errors = error
}
);
}
if (!this.errors) {
//route to new page
}
Run Code Online (Sandbox Code Playgroud)
我对Angular 2很新,所以这可能源于我对Observable的工作方式缺乏了解.我在表单上显示数据没有问题,但无法弄清楚如何在ts组件中看到它.我真的只想检查http create的成功/失败.
Jos*_*ier 103
如相关RxJS文档中所述,如果没有错误,该.subscribe()
方法可以采用在完成时调用的第三个参数.
以供参考:
[onNext]
(Function
):调用可观察序列中每个元素的函数.[onError]
(Function
):在可观察序列的异常终止时调用的函数.[onCompleted]
(Function
):在可观察序列的正常终止时调用的函数.
因此,您可以在onCompleted
回调中处理路由逻辑,因为它将在正常终止时被调用(这意味着在调用时不会出现任何错误).
this.httpService.makeRequest()
.subscribe(
result => {
// Handle result
console.log(result)
},
error => {
this.errors = error;
},
() => {
// 'onCompleted' callback.
// No errors, route to new page here
}
);
Run Code Online (Sandbox Code Playgroud)
作为旁注,还有一种.finally()
方法,无论呼叫成功/失败,都会在完成时调用.这在您总是希望在HTTP请求之后执行某些逻辑而不管结果的情况下(例如,用于记录目的或某些UI交互,例如显示模态),这可能会有所帮助.
Rx.Observable.prototype.finally(action)
在源可观察序列正常或异常终止后调用指定的操作.
例如,这是一个基本的例子:
import { Observable } from 'rxjs/Rx';
import 'rxjs/add/operator/finally';
// ...
this.httpService.getRequest()
.finally(() => {
// Execute after graceful or exceptionally termination
console.log('Handle logging logic...');
})
.subscribe (
result => {
// Handle result
console.log(result)
},
error => {
this.errors = error;
},
() => {
// No errors, route to new page
}
);
Run Code Online (Sandbox Code Playgroud)
Vel*_*ria 22
请注意,从 6.4 开始,以前的回调语法已被弃用,并将在 8.0 中删除。代替
of([1,2,3]).subscribe(
(v) => console.log(v),
(e) => console.error(e),
() => console.info('complete')
)
Run Code Online (Sandbox Code Playgroud)
你现在应该使用
of([1,2,3]).subscribe({
next: (v) => console.log(v),
error: (e) => console.error(e),
complete: () => console.info('complete')
})
Run Code Online (Sandbox Code Playgroud)
https://rxjs.dev/deprecations/subscribe-arguments
您可以通过以下方式实现
this.projectService.create(project)
.subscribe(
result => {
console.log(result);
},
error => {
console.log(error);
this.errors = error
}
);
}
if (!this.errors) {
//route to new page
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
81053 次 |
最近记录: |