在我的angular 2应用程序中,我正在进行从组件到服务以及从服务到后端Web API的调用。从Web API获得的响应从服务发送回组件,我订阅组件内的响应。对于错误处理,我使用的是在整个应用程序中使用的常见错误组件。此错误组件用作其他组件内的模式弹出窗口。如果发生错误,此模式会弹出“重试”按钮。目前,单击“重试”按钮会重新加载整个页面。但是当用户单击“重试”按钮时,我想再次进行失败的Web API调用而不重新加载整个页面。如果此调用在重试时成功,则正常执行流程应继续而不会出现任何中断。我可能不得不使用http请求拦截器的角度2和承诺,但我无法弄清楚如何实现它们。能帮我找到解决方案吗?
来自我的component.ts文件的调用:
this._accountdetailsService.getContacts(this.group.id)
.subscribe(
contacts => this.contacts = contacts,
error => this.callErrorPage(error);
);
_accountdetailsService是服务的一个实例。
从service.ts文件调用后端Web API:
getContacts(groupId: number): any {
return this._http.get(this._serverName + 'api/CustomerGroups/' + groupId + '/contacts')
.map(response => {
if(response.status < 200 || response.status >= 300) {
throw new Error('This request has failed' + response);
}
else {
return response.json();
}
});
}
component.ts文件中的错误处理:
callErrorPage(error: any) {
this.error = error;
this.showErrorModal();
}
onRetry() {
this.hideErrorModal();
window.location.reload();
}
showErrorModal(): void {
this.errorModal.show();
}
hideErrorModal(): void {
this.errorModal.hide();
}
在每个其他组件的模态内部使用的常见错误组件如下所示:
error.component.ts
export class ErrorDetails implements OnInit {
@Input() error;
@Output() onRetry = new EventEmitter();
private sub: any;
errorStatustext: string;
errorMessage: string;
constructor(private _route: ActivatedRoute) { }
ngOnInit() {
if (this.error.status == 0 || this.error.status == 500) {
this.errorStatustext = "Sorry! Could not connect to server."
}
else {
this.errorStatustext = this.error.statusText;
var responseBody = JSON.parse(this.error._body);
if (responseBody) {
this.errorMessage = responseBody.resultText;
}
}
}
onRetryClick() {
this.onRetry.emit();
}
答案 0 :(得分:1)
我不确定我的想法是否切合实际。我想尝试一下。
在你的component.ts中:
retryAction: any;
callErrorPage(error: any, retryAction: any) {
this.error = error;
this.retryAction = retryAction;
this.showErrorModal();
}
onRetry() {
this.hideErrorModal();
//window.location.reload();
this.retryAction();
}
onGetCountacts() {
let that = this;
this._accountdetailsService.getContacts(this.group.id)
.subscribe(
contacts => this.contacts = contacts,
error => this.callErrorPage(error, () => { that.onGetCountacts(); });
);
}