【问题标题】:How can I get only the object with my arrays returned from a function with a promise?如何仅获取从具有承诺的函数返回的数组的对象?
【发布时间】:2015-07-28 09:24:30
【问题描述】:

我希望将 res 中的数据传递给我的 notes 变量。但它返回一个更大的嵌套对象。为什么会这样? 如果我在控制台中检查 cleanArrayOfNotes 的值,我会得到我想要的对象,但是一旦将其分配给注释,它就会变成一个更大的对象。我明白这是 Promises 本质的一部分,目前我仍在努力理解。有什么帮助吗?

notes_service.js

var notesService = {notesObjectInService: [], newNote: null};


    notesService.getAll = function() {
        return $http.get('/notes.json').success(function(data){
            //console.log(data)
            angular.copy(data, notesService.notesObjectInService);
            //console.log(notesService)
        })
    };

navCtrl.js

var notes = notesService.getAll().then(function(res){

            var cleanArrayOfNotes = res.data;
            //navCtrl line12
            console.log(cleanArrayOfNotes);
            return cleanArrayOfNotes;
        });
        //navCtrl line16
        console.log(notes);

【问题讨论】:

  • 您将函数分配给 notes 变量,因此它将是返回 $http 承诺的 getAll()。因此,您的 notes 变量是一个承诺,您的 cleanArrayOfNotes 是已解析的数据
  • 那么我怎样才能将解析后的数据分配给一个局部变量呢?
  • 在 promise 中赋值。
  • notes 是对cleanArrayOfNotes 的承诺。你还期待什么?是否有一些适用于 notes 的代码不起作用?

标签: javascript angularjs promise


【解决方案1】:

这应该适合你:

notes_service.js

app.factory ('NoteService', function($http) {
    return {
        getAll: function() {
            return $http.get('/notes.json').then(function(response) {
                  return response.data;
            });
        }
    }
});

navCtrl.js

    NotesService.getAll().then(function(res){

        $scope.cleanArrayOfNotes = res.data;

    });

或者,如果你想返回结果而不是承诺,你可以:

notes_service.js

app.factory ('NoteService', function($http) {
    var notes = [];
    var promise = $http.get('/notes.json').then(function(response) {
          angular.copy(response.data, notes);
          return notes;
    });    

    return {
        getAll: function() {
            return notes; 
        },
        promise: promise
    }
});

navCtrl.js

     // get array of notes
     scope.cleanArrayOfNotes = NotesService.getAll();

     // or use promise
     NoteService.promise.then(function(response) {
         scope.cleanArrayOfNotes = response.data;
     });

【讨论】:

  • 最后一个选项有竞争条件。
  • 你能解释一下吗?
  • 如果控制器代码运行时getAll中的注释没有加载怎么办?没有什么告诉它等待它,使其避免竞争条件的方法是在路由器或其他机制中使用resolve:
  • 然后,它会返回空的 notes 数组。 angular.copy 用于保存参考。这是 Angular 中的常见模式。这不是竞争条件。 NgResource 就是基于这种模式。
猜你喜欢
  • 1970-01-01
  • 2020-10-11
  • 1970-01-01
  • 2018-08-25
  • 2018-05-16
  • 1970-01-01
  • 2017-04-27
  • 2017-04-05
相关资源
最近更新 更多