为什么无法获取$ http服务的数据?

时间:2017-07-18 06:05:43

标签: angularjs

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>First AngularJS Application</title>
    <script src="scripts/angular.js"></script>

</head>
<body ng-app = "myAngularApp">
<div>
        <div ng-controller="myController">
            Response Data: {{data}} <br />
            Error: {{error}}
        </div>
    </div>
    <script>
        var myApp = angular.module('myAngularApp', []);

        myApp.controller("myController", function ($scope, $http) {

            var onSuccess = function (data, status, headers, config) {
                $scope.data = data;
            };

            var onError = function (data, status, headers, config) {
                $scope.error = status;
            }

            var promise = $http.get("index.html");

            promise.success(onSuccess);
            promise.error(onError);

        });
    </script>
</body>

This is the html file and when I load the page the data were not retrieved. I'm not sure if I have some little mistakes since I copy pasted it in the tutorial. This will be the output.

Folder Structure

2 个答案:

答案 0 :(得分:1)

脚本标记在您的情况下是错误的。您在代码中使用小写但您的文件夹结构显示大写脚本

<script src="Scripts/angular.js"></script>

<强>更新 如果您使用的是最新版本的angularjs,请尝试使用以下代码,因为不推荐使用成功和错误。

 var myApp = angular.module('myAngularApp', []);

        myApp.controller("myController", function ($scope, $http) {

            var onSuccess = function (data) {
                $scope.data = data.data;
            };

            var onError = function (data) {
                $scope.error = data;
            }

            var promise = $http.get("index.html");

            promise.then(onSuccess);
            promise.catch(onError);

        });

了解详情Why are angular $http success/error methods deprecated? Removed from v1.6?

答案 1 :(得分:-1)

使用然后而不是成功并使用捕获而不是错误

示例:

<div>
    <div ng-controller="myController">
        Response Data: <span ng-bind-html="data"></span> <br />
        Error: {{error}}
    </div>
</div>
<script>
    var myApp = angular.module('myAngularApp', []);

    myApp.controller("myController", function ($scope, $http, $sce) {

        var onSuccess = function (data, status, headers, config) {
            $scope.data = $sce.trustAsHtml(data.data);
        };

        var onError = function (data, status, headers, config) {
            $scope.error = data;
        }

        var promise = $http.get("index.html");

        promise.then(onSuccess);
        promise.catch(onError);

    });
</script>