gpt4 book ai didi

javascript - Angularjs 处理 promise 和模型

转载 作者:行者123 更新时间:2023-11-30 05:31:01 25 4
gpt4 key购买 nike

我想知道解决 angularjs 模型与 promises 之间有很多关系的最佳方法是什么。请允许我举一个例子,如果有更好的方法来实现这一点,我很乐意收到您的反馈。

一个 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

以及对应的 Controller :

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])

实际上,问题是:在 Controller 中,我调用函数 Surah.new() 然后继续从后端获取 Surah,然后想要创建它关联的 Ayahs,我将 Ayah 模型注入(inject)到 Surah 模型中,并对 Ayah 做出 promise > 在 Surah 模型中被消化的模型,在 Surah.new() 函数的总体 promise 中。

这是执行此操作的正确方法吗?有没有更好的方法?

最佳答案

进行一次 API 调用可能会引起争议,它会返回您需要的所有内容,但有令人信服的理由可以采用另一种方式。没有一般规则。有关在此处组合 API 请求的更多详细信息:https://softwareengineering.stackexchange.com/q/252362/20893

假设 API 如您所描述的那样,在加载 Ayahs 之前响应对 Surah 的第一次调用可能会有优势,但同样,也有令人信服的理由以其他方式进行。

如果 Surah 中有不依赖 Ayahs 的有用信息,您可以渲染它,然后每次加载 Ayah 时,也将其渲染到页面中(这需要更加注意在界面中正确显示加载微调器在适当的情况下,优雅地处理错误等...)。

如果信息仅在完整加载时才有用,那么您现在拥有它的方式对我来说非常合理。

关于javascript - Angularjs 处理 promise 和模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27076120/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com