在Angular中,异步请求追加到字符串

Asynchronous Request Appending to String in Angular

本文关键字:追加 字符串 请求 异步 Angular      更新时间:2023-09-26

我试图从与页面相关的所有样式表中获取实际文本。我可以通过像

这样的命令来做得很好
sheets = document.styleSheets
stylesheet_text = "<style type='text/css'>"
_.each(sheets, (sheet) ->
  if $(sheet).attr("href")
    $http.get($(sheet).attr("href"))
      .success (data) ->
        console.log data # Displays the text perfectly
        stylesheet_text += data # Never gets appended to.
      .error (data) ->
        console.log "error"
)
stylesheet_text += "</style>"
console.log stylesheet_text

问题是最终的console.log没有显示正确的数据。而是返回

<style type='text/css'></style>

在此之后,console.log data着火并开始吐出文本。哦,异步问题!一个承诺就能解决这个问题,对吗?

getCSSFile = (href) ->
    def = $.Deferred()
    $http.get(href)
      .success (data) ->
        def.resolve(data)
    def.promise()

css = ->
    sheets = document.styleSheets
    stylesheet_text = "<style type='text/css'>"
    _.each(sheets, (sheet) ->
      if $(sheet).attr("href")
        getCSSFile($(sheet).attr("href")).then( (data) ->
          stylesheet_text += data
        )
    )
    stylesheet_text += "</style>"
    console.log stylesheet_text
    stylesheet_text

嗯…不完全是。这仍然不起作用。所以,我决定只走一条我认为我知道会起作用的路线。

ss = ->
    sheets = document.styleSheets
    stylesheet_text = "<style type='text/css'>"
    _.each(sheets, (sheet) ->
      if $(sheet).attr("href")
        $.get($(sheet).attr("href")).then( (data)->
          stylesheet_text += data
        )
    )
    stylesheet_text += "</style>"
    stylesheet_text

就像前面一样,jQuery请求不像我期望的那样填充stylesheet_text变量。

在函数结束返回之前,我能做些什么来确保文本实际上附加到变量上?

首先,你可能不应该在Angular中使用那么多jQuery,也就是说——Angular已经提供了deferred和promises, $http可以很好地取代$.get

现在对于你的问题,我的CoffeeScript有点生锈,但你应该链接承诺:

ss = ->
    sheets = document.styleSheets
    text = "<script type = 'text/css'>";
    links = sheet.href for sheet in sheets when sheet.href? 
    # now chain them all
    links.reduce((p, c) -> p.then( -> $http.get(c).then(data -> text += data)),$q.when())
         .then(val -> val + "</style>")

现在你可以这样做:

ss.then(text -> console.log text)