【问题标题】:how to use the get() function in the $http service如何在 $http 服务中使用 get() 函数
【发布时间】:2016-10-30 17:28:45
【问题描述】:

我学习了 $http 服务,但我不清楚关于 get()。下面的代码不执行 demo2.htm。请检查并告知我在哪里犯了错误。

var app = angular.module('myApp', []);
app.controller('urlCtrl', function($scope, $http) {
  $http.get('demo2.htm').then(function(response) {
      $scope.myWelcome = response.data;
  });
});

【问题讨论】:

  • 控制器是否使用过?如果它不执行,控制器可能没有加载
  • 默认数据类型是 "json" 但你得到一个.htm 文件。你想用它做什么?也为这种情况添加错误处理程序
  • 我想使用 $http.get() 函数查看当前文件中的另一个 HTML 文件
  • 看过下面的学习网站“w3schools.com/angular/angular_http.asp

标签: html angularjs angularjs-directive angular-http


【解决方案1】:

如果您尝试从与您的 html/js 文件相同的位置访问资源,那么 $http 服务似乎不是您想要的。以下其中一项应该更适合您的情况:

【讨论】:

    【解决方案2】:

    试试这个

    var app = angular.module('myApp', []);
    app.controller('urlCtrl', [
        '$scope',
        '$http',
        function($scope, $http) {
          $http.get('demo2.htm').then(function(response) {
              $scope.myWelcome = response.data;
          }
    }]);
    

    【讨论】:

    • 谢谢,相同的代码将在 w3c 教程上运行,但在我的本地系统上显示问题。
    • 今天的欢迎词是:

      {{myWelcome}}

      var app = angular.module('myApp', []); app.controller('urlCtrl', ['$scope', '$http', function($scope, $http) { $http.get('demo2.htm').then(function(response) { $scope. myWelcome = response.data; } }]);
    • 因为您是在本地运行它,所以它无法发出该请求。您可以使用http-server 来解决此问题,并在此处阅读如何开始使用角度docs.angularjs.org/tutorial
    猜你喜欢
    相关资源
    最近更新 更多
    热门标签