我被我所采用的方法所困扰,可能是因为我缺乏关于 Angular Promise VS Restangular Promise 等方面的知识。
我有一个带有 TypeScript 的 AngularJs 应用程序(尽管 typescript 在这里几乎无关紧要,同样适用于任何 javascript)。这些是球员:
export interface IRegistrationService {
addRegistration(model: registration.BusinessRegistration): ng.IPromise<void>;
}
这是我到目前为止所拥有的:
restangular 错误拦截器
restangularProvider.setErrorInterceptor((response: restangular.IResponse, deferred: ng.IDeferred<any>, responseHandler: any) => {
if (response.status === 400) {
let validationError: myTsd.IApiValidationErrors = getAsValidationError(response.data);
// How to pass this validationError as an errorCallback to the controller?
//deferred.notify(validationError);
//deferred.reject(validationError); //this stops the chain
//return true; // if error not handled. But where to put the validationError?
//return false; // if error handled. But where to put the validationError?
}
});
使 Controller 不知道任何关于restangular的服务请注意,它应该返回一个 Angular Promise,而不是一个 RestAngular Promise。
public addRegistration(model: registration.BusinessRegistration): ng.IPromise<void> {
return this.restangular.all("registration")
.post<registration.BusinessRegistration>(model)
.then(() => {
console.log("Registration posted successfully");
}, (error: any) => {
//if I get the object here, how to make it available in the errorCallback of the controller caller?
}, (notify: any) => {
//if I get the object here, how to make it available in the errorCallback of the controller caller?
});
}
使用该服务但对restangular一无所知的 Controller
//public static $inject = ["app.services.RegistrationService"];
//.. controller code
this.registrationService.addRegistration(this.model)
.then(() => {
console.log("model posted successfully in remote API")
}, (error: myTsd.IApiValidationErrors) => {
// if there was any validation error I need the object here
console.log(error);
});
我应该如何链接所有内容?我的“唯一”要求是:
非常感谢!
我不完全理解这里的文档 https://github.com/mgonto/restangular#seterrorinterceptor以及除了通知或拒绝之外,我还能做些什么。
最佳答案
Restangular的.setErrorInterceptor()
是一种相当奇怪的野兽,据我所知,它不会做你想让它做的事情。
它可以感知错误代码(例如您的 400)并在出现这种情况时执行操作,但除了返回 false(阻止)或返回任何其他内容(不阻止)之外没有其他能力。
因此想到
.setErrorInterceptor()
作为“选择性拦截器”,而不是“过滤器”或“捕获”,并将其与 promise.catch()
进行对比行为,由此:.setErrorInterceptor()
的无能为力传播原始错误以外的任何内容似乎可以减轻它的影响,有利于命名的“捕获处理程序”(例如 getAsValidationError()
或包装 getAsValidationError()
的函数),可以包含在任何相关的地方。那应该为您提供所需的功能。我能预见的唯一问题是让 catch 处理程序识别“400”条件 - 可能很简单 - 需要研究。
不要太拘泥于 Angular 的 promise 和 Restangular。它们应该互操作。
关于angularjs - Restangular错误拦截器-如何将自定义对象传递给不了解restangular的 Controller ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35469006/