3

I'm learning Angular and I don't like my current approach. The current controller uses first Geolocation service and when getLocation() is resolved, then the Pagination service is invoked with the location param. Is there any better solution to provide one service that query server with location? Can I integrate current logic and move or use the Pagination service directly through Post factory, and query server with params of given page and location once resolved? I would like to load new data through invoke just one resource method e.g. from scope loadPage() function. How can I refactor this code?

app.controller('MainCtrl',['$scope','Post','Pagination','Geolocation'
  ($scope, Post, Pagination, Geolocation) ->
    $scope.posts = []
    Geolocation.getLocation().then (location) ->
      Pagination.paginate $scope, Post, 10, (postsRes) ->
        $scope.posts.push posts for posts in postsRes
      , params: {location: location}
])

app.factory 'Post', ($resource) ->
  $resource '/posts/:id.json', { id: '@id' }

app.service "Geolocation", ['$q', '$window', ($q, $window) ->
  @getLocation = ->
    deferred = $q.defer()
    return deferred.resolve @loc if @loc
    if $window.navigator and $window.navigator.geolocation
      $window.navigator.geolocation.getCurrentPosition (position) ->
        @loc = position.coords
        deferred.resolve position.coords
    deferred.promise
]
app.service 'Pagination', ->
  @paginate = ($scope, @resource, @maxElemPerPage=10, @onNewPage, @query={}) ->
    @page = 1
    @canLoadNextPage = true
    $scope.loadPage = (promise) =>
      return promise.resolve() unless @canLoadNextPage
      @load promise

    @load = (promise) =>
      @canLoadNextPage = false
      q = angular.extend @query, page: @page
      @resource.query q, (resources) =>
        @canLoadNextPage = true if resources.length is @maxElemPerPage
        @page++
        @onNewPage resources if @onNewPage
        promise.resolve() if promise

    @load()
  @
luzny
  • 2,380
  • 7
  • 30
  • 64
  • Are you asking if you can call the Pagination service from the Geolocation & Post services? – gonzofish Feb 15 '15 at 09:39
  • I would like to move and integrate Pagination logic to Post resource and pass to them resolved location, so in MainCtrl I would like to have only sth like Post.getPostsByLocation() that provide current functionality automatically. – luzny Feb 15 '15 at 11:13

1 Answers1

1

Create a single service that wraps both, have it create it's own promise do the calls and declare the callbacks for both services and return the promise. Once the second service returns, resolve your promise.

bluehallu
  • 10,205
  • 9
  • 44
  • 61