使用AngularJS使用Web Api

时间:2014-08-24 03:26:04

标签: angularjs asp.net-web-api

我从AngularJS开始,我做了这个例子:

一个简单的html文件:

<!DOCTYPE html>
<html ng-app="app" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>First Demo</title>
</head>
    <body>
        <div ng-controller="prdController">
            <div>
                <h2>All Products - With Angular</h2>
                <ul>
                    <li ng-repeat="product in products">
                        {{ formatItem(product) }}
                    </li>
                </ul>
            </div>
            <div>
                <h2>Search by ID</h2>
                <input type="text" ng-model="prodId" size="5" />
                <input type="button" value="Search" ng-click="find(prodId);" />
            </div>
            <strong ng-show="loading">loading..</strong>
            <strong>{{ error }}</strong>
        </div>

        <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.4/angular.min.js"></script>
        <script src="ProductController.js"></script>
    </body>
</html>

我有这个控制器:

(function () {
    var uri = '/demo.WebApi/api/products';
    var app = angular.module('app',[]);

    app.controller('prdController', function ($scope, $http) {
        //debugger;
        $scope.loading = true;
        $scope.products = [];
        //$scope.prodId = 0;
        $scope.error = '';

        $http.get(uri)
            .success(function (data) {
                $scope.products = data;
                $scope.loading = false;
            })
            .error(function () {
                $scope.error = "An Error has occured while loading posts!";
                $scope.loading = false;
        });

        $scope.formatItem = function (item) {
            //debugger;
            return item.Name + ': $' + item.Price;
        }

        $scope.find = function (id) {
            debugger;
            $scope.loading = true;
            $http.get(uri + '/' + id)
            .success(function (data) {
                debugger;
                $scope.products = [];
                $scope.products = data;
                $scope.loading = false;
            })
            .error(function () {
                $scope.error = "An Error has occured while loading posts!";
                $scope.loading = false;
            });
        };
    });
})();

$ http.get方法效果很好,我可以获得我的产品列表。在我的html页面中,我看到了格式化的产品列表:

Tomato Soup: $1
Yo-yo: $3.75
Hammer: $16.99

但是当我尝试搜索一个产品时,在输入文本prodId中输入Id,我看不到该产品。我可以看到返回的数据与我的产品的值,但它不能在我的页面中呈现。该清单如下所示:

undefined: $undefined
undefined: $undefined
undefined: $undefined
undefined: $undefined

我得到第一个列表的3行,再加上我搜索过的产品的一行。

我做错了什么?

谢谢, 马塞洛。

1 个答案:

答案 0 :(得分:0)

GET by ID是否返回一个包含单个对象项或对象的数组?

我怀疑错误是它返回了一个对象,这样当你将返回数据分配给$ scope.products时:

$scope.products = [];
$scope.products = data;

产品不再是阵列。 ng-repeat也接受对象集合,我的猜测是你看到的未定义输出是每个键被传递给formatItem函数的结果。尝试将上述内容更改为:

$scope.products = [data];

如果数据是一个数组,那肯定存在另一个问题。