does this promise look correct?

蓝咒 提交于 2019-12-20 06:38:30

问题


this seems like it should be delivering data to my scope, but it isn't, is there anything that directly jumps out as wrong with the below code ?

angular.module('Lunch.services', [])
  .factory 'LunchMates', ($q, $http) ->
    LunchMates = 

      getLunchMates: () ->
        d = $q.defer(); 
        $http.get('/lunchers').then (response, status) ->
          if response.status == 200
            d.resolve(response.data)
        return d.promise

    return LunchMates


angular.module('Lunch.controllers', [])
  .controller('LunchCtrl', ($scope, LunchMates) ->
    $scope.lunchers = LunchMates.getLunchMates()
  )

回答1:


This code: $scope.lunchers = LunchMates.getLunchMates() sets a promise on the scope, it relies on an old deprecated functionality.

As of version >=1.2, promise unwrapping is deprecated, this is the breaking commit:

This commit disables promise unwrapping and adds $parseProvider.unwrapPromises() getter/setter api that allows developers to turn the feature back on if needed. Promise unwrapping support will be removed from Angular in the future and this setting only allows for enabling it during transitional period.

..........

Previously promises found anywhere in the expression during expression evaluation would evaluate to undefined while unresolved and to the fulfillment value if fulfilled.

..........

BREAKING CHANGE: $parse and templates in general will no longer automatically unwrap promises. This feature has been deprecated and if absolutely needed, it can be reenabled during transitional period via $parseProvider.unwrapPromises(true) api.

You can still enable it with $parseProvider like so:

angular.module('Lunch.controllers', [])
  .config( ($parseProvider) ->
    $parseProvider.unwrapPromises(true)
    $parseProvider.logPromiseWarnings(false)
  )

But it would break in future versions (as mentioned above), so instead do this:

angular.module('Lunch.controllers', [])
  .controller( 'LunchCtrl', ($scope, LunchMates) ->
    LunchMates.getLunchMates().then (data)->
      $scope.lunchers = data
  )

This issue (among some others) is very common, mostly because lots of tutorials & books that new developers find all over the web, was written before version 1.2 and therefore not up-to-date. Always keep yourself up-to-date with the https://github.com/angular/angular.js/blob/master/CHANGELOG.md



来源:https://stackoverflow.com/questions/21546136/does-this-promise-look-correct

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!