2015-07-22 31 views
0

我有一个着陆页的控制器。我的问题是$http每次查看页面后都会被再次调用,因为该视图的控制器被执行,导致$http一直在执行。

app.controller('landingCtrl', function($scope, $splash, $http, sentiment) { 

    //get JSON DATA FROM SERVER 
    var restURL = {}; 
    restURL.getSentiments = "http://localhost:3000/getSent"; 

    //get JSON DATA FROM SERVER 
    $http.get(restURL.getSentiments).then(function(res) { 
     log(res); 
     return res; 
    }); /*AJAX ENDS*/ 

}); 

有什么办法,我打电话给我的$http只有一次或有控制的一些自由,当我要打电话?截至目前$http总是得到执行。

+0

你可以用你的'$ http' GET请求到一个函数,并调用它任意次数。 –

+3

或者你可以将它包装到一个服务中,该服务将结果保存在一个变量中,并且只要它已经被ur $ http调用设置就返回该变量。 – BastianW

回答

1

为了保持我的代码清洁和结构化,我将这些$ http调用包装在服务中。另外,当你有不同的REST调用时,当你不得不编辑你的api路径时,你需要更少的代码来改变。

下面是一个例子:

'use strict'; 

angular.module('YourApp') 
    .service('Sentiments', function ($http) { 
    var sentiments = []; 
    var api = 'http://localhost:3000/getSent'; 

    return { 
     all: function(callback) { 
      var cb = callback || angular.noop; 
      if(sentiments.length !== 0) { 
       cb(sentiments); 
      }else{ 
       $http.get(api) 
        .success(function(result) { 
         sentiments = result; 
         cb(result); 
        }) 
        .error(function() { 
         cb(); 
        }) 
      } 
     } 
    } 
    }) 

    .controller('landingCtrl', function ($scope, Sentiments) {   
    Sentiments.all(function(sentiments) { 
     $scope.sentiments = sentiments; 
    }); 
    }); 
0

允许从功能编程indrocude once。由于使用fn变量来确保该函数仅执行一次,因此被封装的函数仅被触发一次。

angular.module('app', []) 
 
    .controller('onceCtrl', function($scope, messages) { 
 

 
    $scope.messages = messages.get() 
 

 
    }).factory('messages', function($timeout, once) { 
 

 
    var messages = [] 
 

 
    return { 
 
     get: once(function() { 
 
     $timeout(function() { // some delay to simulate $http request 
 
      messages.push({ 
 
      date: Date.now() 
 
      }) 
 
     }, 1000) 
 
     return messages 
 
     }) 
 
    } 
 

 

 
    }).factory('once', function() { 
 
    return function once(fn, context) { 
 
     var result; 
 

 
     return function() { 
 
     if (fn) { 
 
      result = fn.apply(context || this, arguments); 
 
      fn = null; 
 
     } 
 

 
     return result; 
 
     }; 
 
    } 
 
    });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> 
 

 
<div ng-app="app"> 
 
    <div ng-controller="onceCtrl"> 
 
    First exection {{ messages }} 
 
    </div> 
 
    <div ng-controller="onceCtrl"> 
 
    Second execution {{ messages }} 
 
    </div> 
 
    <div ng-controller="onceCtrl"> 
 
    Third execution {{ messages }} 
 
    </div> 
 
</div>

相关问题