javascript - 如何访问从同一控制器中服务块外部的 api 接收的数据
问题描述
我正在使用 Angular 1.7.8,并且我有一个控制器调用从 API 接收数据的服务,问题是,我无法访问同一控制器中服务块之外的数据。
app.controller('AppController', function ($scope, DataService) {
let fieldProperties = {};
$scope.findInData = function (value) {
DataService.getData().then(function (response) {
$scope.result = response.data;
if (response.data !== undefined) {
for (let idx in $scope.result) {
if ($scope.result.hasOwnProperty(idx)) {
if (value === $scope.result[idx].fieldname) {
fieldProperties = {
'fieldName': $scope.result[idx].fieldname,
'preferredFieldName': $scope.result[idx].preferredfieldname,
'fieldValue': $scope.result[idx].fieldvalue,
'isEditable': $scope.result[idx].editable,
'isMandatory': $scope.result[idx].mandatory,
'isAutoClear': $scope.result[idx].autoclear
};
}
}
}
}
});
};
$scope.resultFieldProperties = fieldProperties;
});
另外我想提一下,直接将 $scope 放在 fieldProperties 上对我来说不是一个解决方案,因为我需要将此结果发送到指令范围,fieldProperties 对象因为范围在服务块之外也是未定义的,请提供其他建议!?
解决方案
您可以通过调用函数将结果返回给您的变量
$scope.findInData = function (value) {
DataService.getData().then(function (response) {
$scope.result = response.data;
if (response.data !== undefined) {
for (let idx in $scope.result) {
if ($scope.result.hasOwnProperty(idx)) {
if (value === $scope.result[idx].fieldname) {
fieldProperties = {
'fieldName': $scope.result[idx].fieldname,
'preferredFieldName': $scope.result[idx].preferredfieldname,
'fieldValue': $scope.result[idx].fieldvalue,
'isEditable': $scope.result[idx].editable,
'isMandatory': $scope.result[idx].mandatory,
'isAutoClear': $scope.result[idx].autoclear
};
return fieldProperties;
}
}
}
}
});
};
$scope.resultFieldProperties = $scope.findInData('<some_value>');
否则,您需要有一个回调函数作为参数,并且可以在完成时向您返回数据。
推荐阅读
- serverless - serverless-bundle 缺少依赖项
- python - 如何将 Dataframe 时间增加 5 分钟?
- c++ - 数组,比较数组的两个元素,简单的纸牌游戏,c++
- python - 遇到索引错误问题(Python)
- javascript - 有没有办法在浏览器执行 javascript 之前注入代码片段?
- html - href 链接不起作用-当我单击链接 simka1.html 时它不起作用,可能是许多 div 标签?-
- windows-7 - 当销毁一个窗口时,另一个窗口出现修复
- r - 在 For 循环中使用 Rvest 和 SelectorGadget (Sreality) 进行网页抓取
- object - sqlalchemy.exc.InvalidRequestError:对象已附加到会话“2”(这是“3”)
- php - 读取csv文件内容