角度2-检查来自订阅的服务器错误

我觉得这种情况应该出现在角度2的文档中,但我到处都找不到。

情况是这样的

  1. 提交在服务器上无效的表单(创建对象)
  2. 服务器返回一个400个错误请求,其中包含我在表单上显示的错误
  3. 在订阅返回后,我想检查一个错误变量或其他东西(即。如果没有错误 > ,则路由到新创建的详细信息页面)

我想它的工作原理是这样的:

this.projectService.create(project)
.subscribe(
result => console.log(result),
error => {
this.errors = error
}
);
}


if (!this.errors) {
//route to new page
}

我对角度2很陌生,所以这可能是因为我对可观测物体的工作原理缺乏理解。在表单上显示这些数据没有问题,但是不知道如何在 ts 组件中查看它们。我真的只是想检查 http 创建的成功与失败。

195501 次浏览

As stated in the relevant RxJS documentation, the .subscribe() method can take a third argument that is called on completion if there are no errors.

For reference:

  1. [onNext] (Function): Function to invoke for each element in the observable sequence.
  2. [onError] (Function): Function to invoke upon exceptional termination of the observable sequence.
  3. [onCompleted] (Function): Function to invoke upon graceful termination of the observable sequence.

Therefore you can handle your routing logic in the onCompleted callback since it will be called upon graceful termination (which implies that there won't be any errors when it is called).

this.httpService.makeRequest()
.subscribe(
result => {
// Handle result
console.log(result)
},
error => {
this.errors = error;
},
() => {
// 'onCompleted' callback.
// No errors, route to new page here
}
);

As a side note, there is also a .finally() method which is called on completion regardless of the success/failure of the call. This may be helpful in scenarios where you always want to execute certain logic after an HTTP request regardless of the result (i.e., for logging purposes or for some UI interaction such as showing a modal).

Rx.Observable.prototype.finally(action)

Invokes a specified action after the source observable sequence terminates gracefully or exceptionally.

For instance, here is a basic example:

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
}
);

You can achieve with following way

    this.projectService.create(project)
.subscribe(
result => {
console.log(result);
},
error => {
console.log(error);
this.errors = error
}
);
}


if (!this.errors) {
//route to new page
}

Please note that the previous syntax with callbacks has been deprecated as of 6.4 and is going to be removed with 8.0. Instead of

of([1,2,3]).subscribe(
(v) => console.log(v),
(e) => console.error(e),
() => console.info('complete')
)

you should now use

of([1,2,3]).subscribe({
next: (v) => console.log(v),
error: (e) => console.error(e),
complete: () => console.info('complete')
})

https://rxjs.dev/deprecations/subscribe-arguments