angularjs - 如何使用angularjs在变量中获取函数返回值
问题描述
这是我的 angularjs 文件代码
$scope.httpPost = function (url, json_form_data) {
$http.post(url, json_form_data)
.then(function (response) {
$scope.responseData = response.data;
return $scope.responseData;
}, function (response) {
$scope.content = "Something went wrong";
});
};
这是我调用上述函数的函数
$scope.getAuthToken = function (account_type, auth_type, email, type_of_request) { // type of request means login or signUp
var account_type = account_type;
var form_data = {
'email': email,
"auth_type": auth_type,
"account_type": account_type
};
$scope.responseData = $scope.httpPost($scope.authTokenUrl, form_data);
console.log("value of res");
console.log($scope.responseData);
};
上面代码的输出是
value of res
loginAndSignup.js:138 undefined
我的问题是我如何访问函数返回的值,因为我需要那个值。
我尝试了以下解决方案
$scope.httpPost = function (url, json_form_data) {
return $http.post(url, json_form_data)
.then(function (response) {
return response;
}, function (response) {
$scope.content = "Something went wrong";
});
};
$scope.login = function (email, auth_token, auth_type, account_type) {
var password = $scope.password;
var form_data = {
//form data
};
var url = $scope.loginUrl;
$scope.httpPost(url, form_data)
.then(function (response) {
return response;
}, function (response) {
$scope.content = "Something went wrong";
});
解决方案
using $q
(帮助您异步运行函数的服务,并在完成处理时使用它们的返回值(或异常)。)
使用了这个功能
$scope.httpPost = function (url, json_form_data) {
var d = $q.defer();
$http.post(url, json_form_data)
.then(function (response) {
d.resolve(response);
}, function (response) {
d.reject(response);
});
return d.promise;
};
推荐阅读
- c++ - 如何嵌套这些类和 FlexBox 函数?
- scala - 在哪里可以找到与 spark 结构化流相关的所有属性?
- vue.js - 未捕获的类型错误:无法读取未定义的属性“拼接”
- android - AndroidX 重构:旧的支持库仍在其他第三方库中使用
- javascript - 你把使用函数之外的东西的函数和自包含的函数称为什么?
- css - CSS animation re-played after :hover animation
- spring - Spring/Mockito Junit 测试空指针异常
- ios - IOS/Objective-C/Storyboard:防止 ViewController 模态启动
- jpeg - JPG DHT 中的值顺序
- http - 为 Pintrest 添加 HTTP 和 HTTPS 社交共享计数