在Angular中,异步请求追加到字符串
Asynchronous Request Appending to String in Angular
我试图从与页面相关的所有样式表中获取实际文本。我可以通过像
这样的命令来做得很好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)
相关文章:
- 如何在javascript中无空格地追加两个字符串
- 如何使用串联匿名函数追加到字符串
- 追加并替换data-*属性URL的查询字符串值
- JQuery if 语句基于在文本中包含特定字符串将数据追加到相应的 DIV
- HTML 将变量追加到查询字符串
- 将字符串转换为 jquery 元素并将其追加到 DOM 中
- 使用 For 循环追加.在追加之前将字符串中的字符添加到元素中
- 从多个页面追加查询字符串
- Javascript 在追加到字符串时递减整数
- 有条件地将查询字符串追加到角度 href
- 主干同步覆盖,使用查询字符串追加 URL
- Javascript 字符串在追加为类属性时按空格拆分
- 尝试追加 html 字符串失败与 jQuery
- 如何使用 Jquery 替换或覆盖容器中追加的 html 字符串
- 正在将查询字符串追加到URL
- 查找并追加字符串
- 用匹配的子字符串追加字符串
- Gulp.js在使用gulp.useref后为SRC和href属性追加字符串
- 在输入的特定偏移位置追加字符串
- 在ASP中使用jquery追加c#字符串.Net MVC Razor