无法运行Angular Service

时间:2016-07-04 06:07:12

标签: angularjs model-view-controller asp.net-web-api2

我正在尝试关注LinkedIn中的示例,但遇到以下问题: 1.我尝试调用localhost:portname / Values / GetStates但不是加载页面,而是要求我下载json文件。 2.当我使用F12时,它没有向我显示我添加到项目中的Angular和其他引用,无法理解为什么会这样? 我尝试在页面顶部包含引用,如下所示:

<script src="~/Scripts/angular.js"></script>
<script src="~/Scripts/Controllers/AngularController.js"></script>
<script src="~/Scripts/Services/AngularService.js"></script>
<link href="~/Content/bootstrap.css" rel="stylesheet" />

并使用:

  bundles.Add(new ScriptBundle("~/Scripts/angularscripts").Include(
            "~/Scripts/angular.js",
            "~/Scripts/AngularController.js",
            "~/Scripts/AngularService.js"));

然后包括这样的包引用:

@section Scripts
{
    @Scripts.Render("~/Scripts/angularscripts")

}

但也没有用。

我的代码很简单:

 public class ValuesController : ApiController
{
    [HttpGet]
    public string GetStates()
    {
        List<States> states = new List<States>();
        var state = new States();

        state.Id = 1;
        state.Name = "NSW";
        states.Add(state);

        state.Id = 2;
        state.Name = "QLD";
        states.Add(state);

        state.Id = 3;
        state.Name = "VIC";
        states.Add(state);

        state.Id = 4;
        state.Name = "WA";
        states.Add(state);

        var result = JsonConvert.SerializeObject(states);
        return result;
    }

    [HttpPost]
    public string GetResult(States state)
    {
        var result = "State name is " + state.Name;
        result = JsonConvert.SerializeObject(result);
        return result;

    }

}

和Angular代码是: AngularService.js

AngularModule.service('ApiCall', ['$http', function ($http) {
var result;

this.GetApiCall = function (controllerName, methodName) {
    result = $http.get('api/' + controllerName + '/' + methodName).success(function (data, status) {
        result = (data);
    }).error(function () {
        alert("Some problem in calling the service");
    });
    return result;
};

this.PostApiCall = function (controllerName, methodName, obj) {
    $http.post('api/' + controllerName + '/' + methodName).success(function (data, status) {
        result = (data);
    }).error(function () {
        alert("Some problem in calling the service");
    });
    return result;
};

}]);

AngularController.js

var AngularModule = angular.module('App', []);

AngularModule.controller('AppController', function ($scope, $http, ApiCall)     {
    $scope.message = "This is a test";
    alert('App Controller');

    var result = ApiCall.GetApiCall("Values", "GetStates").success(function (data) {
        alert('data');
        var result = $.parseJSON(JSON.parse(data));
        $scope.StateList = result;
    });

    $scope.btnPostCall = function () {
        var obj = {
            'Name': 'NSW'
        };

        var result = ApiCall.PostApiCall("Values", "GetResult", obj).success(function (data) {
            var result = $.parseJSON(JSON.parse(data));
            $scope.message = result;
        });

    }

});

AngularService.js

AngularModule.service('ApiCall', ['$http', function ($http) {
var result;

this.GetApiCall = function (controllerName, methodName) {
    result = $http.get('api/' + controllerName + '/' + methodName).success(function (data, status) {
        result = (data);
    }).error(function () {
        alert("Some problem in calling the service");
    });
    return result;
};

this.PostApiCall = function (controllerName, methodName, obj) {
    $http.post('api/' + controllerName + '/' + methodName).success(function (data, status) {
        result = (data);
    }).error(function () {
        alert("Some problem in calling the service");
    });
    return result;
};

}]);

我通过将'api / values / getstates'附加到localhost来运行此项目。 任何想法???

    }
}

2 个答案:

答案 0 :(得分:0)

当我在Internet Explorer浏览器中运行angularjs应用程序时,我遇到了类似的问题,但在Firefox和Chrome等其他浏览器中运行良好。在我的情况下,问题是Internet Explorer的注册表设置未设置为显示json,因此它像任何其他文件一样丢弃流下载。

如果适用于您,请参考以下链接中的设置。

How can I convince IE to simply display application/json rather than offer to download it?

答案 1 :(得分:0)

  

嗨,这是完整的示例,您可以了解如何在您的应用程序中使用服务。

        var app = angular.module("app", []);

app.controller("controller", ["$scope","ApiCall", function ($scope, apiCall) {
            var root = 'http://jsonplaceholder.typicode.com';

            apiCall.GetApiCall(root + "/posts").then(function(data) {
                $scope.posts = data;
            });

            $scope.post = function () {
                var command = {
                    title: 'maher',
                    body: 'test',
                    userId: 1
                }
                apiCall.PostApiCall(root + "/posts", command).then(function (response) {
                    console.log(response)
                    $scope.posts.push(response);
                });
            }

        }]);

        app.service("ApiCall", ["$http", "$q", function ($http, $q) {
            this.GetApiCall = function (api) {
                var deferred = $q.defer();

                $http({
                    method: "GET",
                    async: true,
                    url: api
                }).success(function (response) {
                    deferred.resolve(response);
                })
                    .error(function (error) {
                        console.error("HttpRestApp error:", error);
                        deferred.reject(error);
                    });
                return deferred.promise;
            };

            this.PostApiCall = function (api, data) {
                var deferred = $q.defer();

                $http({
                    method: "POST",
                    async: true,
                    data: data, 
                    url: api
                }).success(function (response) {
                    deferred.resolve(response);
                })
                    .error(function (error) {
                        console.error("HttpRestApp error:", error);
                        deferred.reject(error);
                    });
                return deferred.promise;
            };
        }]);
<!DOCTYPE html>
<html ng-app="app" ng-controller="controller as ctrl">
<head>
    <title></title>

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
</head>
<body>

<div class="container">
    <h1>POST</h1>

    <button ng-click="post()">post</button>
  <small>check your console: check last record it will be post</small>

    <div class="clearfix"></div>
    <h1>GET</h1>
    <table class="table table-bordred">
        <tr ng-repeat="post in posts">
            <td>{{post.title}}</td>
        </tr>
    </table>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

</body>
</html>