Angular应用程序中Javascript中的方法链接
在我的Angular web应用程序中,我有一个名为Angular应用程序中Javascript中的方法链接,javascript,angularjs,angular-promise,Javascript,Angularjs,Angular Promise,在我的Angular web应用程序中,我有一个名为ApplicationModule的模块。 ApplicationModule具有get和set功能 在我的一个控制器中,我调用如下函数: ApplicationModule.get().then(function (response) { //do something with response }); GET()函数返回一个名为application的对象。对于返回的对象,我想用它做点什么。因此,我使用then来链接该方法,但我得
ApplicationModule
的模块。
ApplicationModule
具有get
和set
功能
在我的一个控制器中,我调用如下函数:
ApplicationModule.get().then(function (response) {
//do something with response
});
GET()
函数返回一个名为application
的对象。对于返回的对象,我想用它做点什么。因此,我使用then
来链接该方法,但我得到一个错误,即angular.js:13424 TypeError:无法读取未定义的的属性“then”
更新了get()是什么
我做错了什么?方法.then()
仅适用于承诺。为了处理应用程序对象,我建议将值存储为变量
var application = ApplicationModule.get();
foo(application);
如果localStorage.application
为falsy,则您的方法根本不会返回对象
您正在函数中执行异步操作,因此需要始终返回一个承诺:
ApplicationModule.get = function () {
if (!localStorage.application) {
return Rectangular.all('session').one('user').get().then(function (response) {
// ^^^^^^ returning the promise
var application = {
"id": response.current_application_id,
"user_id": response.id,
"visa_type": response.current_type
};
localStorage.setItem("application", JSON.stringify(application));
return application;
// ^^^^^^ returning the value that the promise will resolve with
});
} else {
return $q.resolve(JSON.parse(localStorage.application));
// ^^^^^^^^^^ creating a promise here as well for consistent interface
}
}
.then()
通常仅用于承诺语法。您的.get()
方法不会返回承诺,而是返回一个对象。只需执行var response=ApplicationModule.get()显然,.get()
不会返回对象。如果你想让我们帮助你解决这个问题,你必须向我们展示它的代码。听起来好像ApplicationModule.get不存在(未定义)。你确定它不是GET()?它还需要返回一个承诺。您没有显示get()
返回的内容,只是描述它应该返回一个应用程序
对象。要解决此问题,需要查看get()
方法的完整签名。我只需要在ApplicationModule.get()完全运行后调用某些函数ApplicationModule.get()
和其他函数应该是顺序的,以免在我的应用程序中造成问题。而get()
只返回一个JSON对象。这不适用于我的应用程序。请查看我上面的评论。return restanglar
有什么作用?$q.resolve
做什么?从未遇到过这种情况,因此我希望您能进一步解释。@JoHksiRestangular
只是Bergi的一个输入错误,您应该按照他在“不返回应用程序”中提供的链接进行操作。只需向调用函数发出信号,说明ApplicationModule.get()
返回的承诺已成功完成。@peteb,您是否建议在restanglar之前删除return?如何编写附加函数来捕获错误?在ApplicationModule.get()
?@JoHksi不,我不是,这正是造成您的问题的原因,您没有返回由矩形.all()
创建的承诺。阅读Bergi提供的代码片段中的注释…@JoHksi:不,我们不是建议省略返回值
——我回答的全部要点是,您在原始代码中忘记了它!它确实返回了。然后(…)
调用返回的承诺。
ApplicationModule.get = function () {
if (!localStorage.application) {
return Rectangular.all('session').one('user').get().then(function (response) {
// ^^^^^^ returning the promise
var application = {
"id": response.current_application_id,
"user_id": response.id,
"visa_type": response.current_type
};
localStorage.setItem("application", JSON.stringify(application));
return application;
// ^^^^^^ returning the value that the promise will resolve with
});
} else {
return $q.resolve(JSON.parse(localStorage.application));
// ^^^^^^^^^^ creating a promise here as well for consistent interface
}
}