簡體   English   中英

為什么角負荷內聯模板卻觸發$ http?

[英]Why angular load inline template but trigger the $http?

這有點復雜。 我會盡力解釋我的問題。

首先,我創建一個HttpService來包裝$http以便每個ajax都將觸發#loading元素以顯示請求正在處理。 這是下面的服務。

angular.module('HttpServices', [])
.factory('HttpWrapper', ['$http', '$rootScope', function($http, $rootScope) {
  $http.defaults.transformRequest.push(function(data) {
    $rootScope.loading = ($rootScope.loading ? $rootScope.loading + 1 : 1);
    console.log('start request') # this will be triggered by template load!!
    console.log(data); # the template will be printed to the console!!
    return data;
  });
  $http.defaults.transformResponse.push(function(data) {
    $rootScope.loading -= 1;
    console.log('finish request');
    console.log(data);
    return data;
  });
  return $http;
}]);

然后,我退出了簡單的路線。

@myapp = angular.module('myapp', ['HttpServices'])

myapp.factory('Service', ['HttpWrapper', ($http) ->
  service = {}
  service.data = [1..3]
  service
])

myapp.config (['$routeProvider', ($routeProvider) ->
  $routeProvider
    .when('/', {
      templateUrl: 'home.html',
      resolve: {
        data: ['Service', (Service) ->
          Service.data
        ]
      }
    })
    .when('/test', {
      templateUrl: 'test.html'
    })
])

然后html也非常簡單。

  <div data-ng-app='myapp'>
    <ul>
      <li><a href="#/">home</a></li>
      <li><a href="#/test">test</a></li>
    </ul>
    <div id="loading" ng-show="loading">loading</div>
    <div ng-view></div>
    <script type="text/ng-template" id="home.html">
      home
    </script>
    <script type="text/ng-template" id="test.html">
      test
    </script>
  </div>

看,模板只是內聯模板。 它們只是隱藏ng-view元素。 但是,當我單擊鏈接#/鏈接#/ test時 ,將觸發http包裝器 ,就像發送了ajax請求一樣。 為什么? 它們只是內聯模板。 為什么觸發$http 實際上與后端之間沒有通信。

這是我的解決方案。

myapp.config (['$routeProvider', ($routeProvider) ->
  $routeProvider
    .when('/', {
      template: $('#home_html').html(),
      resolve: {
        data: ['Service', (Service) ->
          Service.data
        ]
      }
    })
    .when('/test', {
      template: $('#test_html').html()
    })
])

我認為關鍵字templateUrl始終會觸發$ http,即使它是嵌入式腳本標簽也是如此。 所以不要使用它。

我也有同樣的問題。 它生成一個新的http請求,因為您放置在內聯腳本標簽上的ID與templateUrl中的ID不匹配。

Angular首先在其內聯模板的內部緩存中檢查那些url,然后才通過網絡實際查找它們

簽出此鏈接在Angular中使用內聯模板

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM