AngularJS调用Rest Api:TypeError

时间:2016-04-07 03:20:44

标签: angularjs rest http

我正在呼叫AngularJS的宁静服务。 HTML是非常基本的,带有输入文本框和查询按钮。

// basic.html

<!DOCTYPE html>
<html ng-app="cgApp" >
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular-resource.js"></script>
    <script src="../js/controller.js"></script>
    <script src="../js/service.js"></script>

  </head>
  <body>
    <div ng-controller="CgseqCtrl">
        <input ng-model="analysisid"><button ng-click="searchById()">Search</button>
        <table>
            <tr>
                <td>{{seq.analysisId}}</td>
                <td>{{seq.center}}</td>
                <td>{{seq.diseaseAbbr}}</td>
                <td>{{seq.filepath}}</td>
                <td>{{seq.library}}</td>
            </tr>
        </table>        
    </div>
  </body>
</html>

我使用服务来调用rest api

// service.js
app.factory("Cgseq", function ($http) {
    // return $resource('http://localhost:8080/cgweb/api/seqs/fdebfd6e-d046-4192-8b97-ac9f65dc2009');
    var service = {};
    service.getSeqById = function(analysisid) {
        return http.get('http://localhost:8080/cgweb/api/seqs/' + analysisid);
    }


    service.getSeq = function() {
        return $http.get('http://localhost:8080/cgweb/api/seqs/fdebfd6e-d046-4192-8b97-ac9f65dc2009');
    }

    return service;
});

单击按钮后将执行函数searchById()。它在我的控制器中实现。

// controller.js
var app = angular.module('cgApp', [])

app.controller('CgseqCtrl', ['$scope', 'Cgseq', function($scope, Cgseq){
    $scope.searchById() = function() {
        CgSeq.getSeqById($scope.analysisid)
        .then(function(response){
            $scope.seq = response;
        });
    }
}]);

当我在浏览器中加载basic.html时,即使在输入框中输入内容并单击按钮之前,我也会收到以下错误:

angular.js:12416 TypeError: $scope.searchById is not a function
    at new <anonymous> (controller.js:8)

1 个答案:

答案 0 :(得分:2)

您应该从()

中删除$scope.searchById() = function

更正Cgseq的拼写错误(区分大小写) 即:

$scope.searchById = function() {
    Cgseq.getSeqById($scope.analysisid)
    .then(function(response){
        $scope.seq = response;
    });
}