Angular JS Promise + Object Constructors

时间:2014-09-15 17:06:22

标签: javascript angularjs promise

这是我的情况。为简单起见,我们假设我有一个名为BookListManager的系统来管理图书馆书籍列表。

app.service('BookListManager', function(){
    var BookListManager = {
        activeBookList:null,
        addNewBookList:function(){
            //create new BookList()
            //set new BookList to activeBookList;
        }
    }
}

然后我有一个创建BookList对象的工厂。

app.factory('BookList', function(){
    var BookList = function(params){
         //RESTful request via resource to fetch booklist data.
         //Assign booklist data to this object.
         //Create Book object for each book in this book list.
    }
    return BookList;
});

现在我有一个Book对象属于每个图书清单。

 app.factory('Book', function(){
     var Book = function(){
        //RESTful resource call for book data.
        //Assign book data to Book object.
     }

     return Book;
 });

如何在BookList和Books完成从AJAX请求中收集数据之后再创建一个promise链,等待它在我的BookListManager服务中指定为activeBookList之前?

我正在使用最新版本的Angular。感谢。

1 个答案:

答案 0 :(得分:0)

嗯,在我看来,构造函数不应该执行任何I / O,因为我认为这应该很简单。但是,鉴于您的编码风格不同,使用您当前的模式,我们别无选择,只能将BookBookList作为承诺:

 app.factory('Book', function(){
     var Book = function(){
         var data = $http.get(...); // or ngResource call
         data.then(function(resp){
            // populate book fields, for example
            this.author = resp.data.author;
         }.bind(this))
         this.then = data.then; // make the book a thenable
     };

     return Book;
 });

这可以让你编写如下代码:

var b = new Book();
b.then(function(){
   // I know the book is loaded here
})

同样,您可以为BookList

执行此操作
app.factory('BookList', function(){
    var BookList = function(params){
         var p = $http.get(...); // fetch book list data, could be ngResource too
         var p2 = p.then(function(list){
             this.listName = list.data.name;
             var booksP = $q.all(list.data.books.map(function(bookId){
                 return new Book(bookId); // fetch param
             });
             return booksP; // return promise over books loading 
         }.bind(this))
         this.then = p2.then; // make this a promise that resolves on load
    };
    return BookList;
});

可以让你这样做:

var bl = new BookList(...);
bl.then(function(){
    // all data in the book list loaded
})