2014-11-22 125 views
2

我想知道什么最好的方法来解决在angularjs模型和承诺之间有很多关系。请允许我举个例子,如果能有更好的实施方法,我会非常乐意提供您的反馈意见。Angularjs处理承诺和模型

一个Surah有很多Ayahs

Surah型号:

angular.module('qurancomApp') 
    .service 'Surah', (Restangular, userOptions, Ayah) -> 

    class Surah 
     constructor: (obj) -> 
     for key of obj 
      @[key] = obj[key] 

     getAyahs: (from, to) -> 
     self = @ 
     @ayahs = Ayah.all 
      surah_id: @id, from: from, to: to 
     .then (ayahs) -> 
      self.ayahs = ayahs 

     @new: (id)-> 
     return Restangular.one('surahs', id).get().then (data)-> 
      return new Surah(data) 

     @all: -> 
     return Restangular.all("surahs").getList() 

Ayah型号:

angular.module('qurancomApp') 
    .service 'Ayah', (Restangular, userOptions) -> 
    # AngularJS will instantiate a singleton by calling "new" on this function 
    class Ayah 
     constructor: (obj)-> 
     for key of obj 
      @[key] = obj[key] 

     @all: (hash) -> 
     Restangular.one('surahs', hash.surah_id).getList 'ayat', 
      content: userOptions.content, quran: userOptions.quran, audio: userOptions.audio 
     .then (data)-> 
      ayahs = data.map (ayah) -> 
      # The ayah object is returned from Restangular and given all the properties that restangular gives it. For example, you can call 
      # ayah.save() or ayah.remove() which will make API calls accordingly. This is power and will be perserved when creating the Ayah object 
      return new Ayah(ayah) 
      return ayahs 

和相应的控制器:

angular.module('qurancomApp') 
    .controller 'AyahsCtrl', ($scope, $routeParams, Surah) -> 
    rangeArray = $routeParams.range.split("-") 

    Surah.new($routeParams.id).then (surah) -> 
     $scope.currentSurah = surah 
     console.log $scope.currentSurah.getAyahs(rangeArray[0], rangeArray[1]) 

真的,问题是:在控制器中,我称之为功能Surah.new(),然后向前走并取入该Surah从后端,然后要创建它相关的Ayahs,这是我注入Ayah模型到Surah模型和有在Surah模型中正在消化的Ayah模型上的承诺,在Surah.new()函数的整体承诺内。

这是一个正确的方法来做到这一点?能有更好的方法吗?

回答

1

可能有一个参数可以让一个API调用返回所需的所有内容,但另一种方式有很多令人信服的理由。没有一般规则。有关在这里组合API请求的更多详细信息,请参阅:https://softwareengineering.stackexchange.com/q/252362/20893

假设API如您所描述的那样,在加载Ayahs之前响应第一次调用Surah可能会有优势,但同样有充分的理由要做到这一点其他方式也一样。

如果在Surah中有一些不依赖Ayahs的有用信息,那么您可以渲染它,然后每次Ayah加载时,也将其渲染到页面中(这需要更加小心地在界面中正确显示,适当的纺纱厂,优雅地处理错误等)。

如果这些信息只在全部加载时才有用,那么现在对于我来说,这种方式看起来非常合理。