【问题标题】:Angular $resource, lose scope variable after function callAngular $resource,函数调用后丢失范围变量
【发布时间】:2016-11-07 20:11:22
【问题描述】:
 var createAttendances = function(){
    var stud = StudentResource.get(function(data){
        $scope.students = data.students;
        console.log($scope.students);
    });
    console.log(stud.students);
    console.log($scope.sudents);
};

在资源获取函数内部,它打印出两个对象的数组(这很好) 将外部资源打印出来 undefined

它看到 stud 对象但是当我查询学生参数时它返回 undefined

如您所见,主要问题是获取 $scope.students 或 data.students ouside StudentResouce.get func

【问题讨论】:

    标签: angularjs angular-resource


    【解决方案1】:
    StudentResource.get
    

    是一个异步调用,这意味着它下面的行甚至可以在 Resource GET 调用完成之前执行,这就是你的变量在回调之外返回 undefined 的原因。

    要访问您通过 GET 调用获取的数据,您必须在回调本身内部对其进行查询。

    【讨论】:

    • var stud = StudentResource.get(function(data){ return data.students; });但我无法查询学生财产
    • 它返回资源 {$promise: Promise, $resolved: false} 但不能查询学生参数
    【解决方案2】:

    这是一个异步调用,所以你可以这样得到结果,我一开始也有同样的困惑。

    StudentResource.get().$promise.then(function (result) {
           $scope.students = result.students;
            console.log($scope.students);
    })
    

    【讨论】:

    • 做一个console.log('result: ' + JSON.stringify(result));检查结果对象
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-06-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-17
    • 1970-01-01
    相关资源
    最近更新 更多