2017-01-23 14 views
0

anglejs 1.4.3で実装されたアプリケーションを実行するたびに、TypeError:角度jsでAPIを呼び出すとサービスが機能しない

BannerService.js

app.service('BannerService',function ($http) { 

    this.save = function saveBanner(banner) { 
     return $http({ 
       method: 'POST', 
       url: 'http://localhost:8081/api/banners' 
      }); 
    } 

}); 

BannerController.js

app.controller('BannerAddCtrl', ['$scope','$log','BannerService', 
    function ($scope,$log, BannerService) { 
     $scope.save = function() { 
      BannerService.saveBanner(myBanner) 
       .success(function (result) { 
        $log.debug('RESULT', result); 
       }, function (reason) { 
        $log.debug('REASON', reason); 
       }); 
     } 

}])。

そしてindex.htmlの

<div class="modal-footer"> 
    <button type="button" class="btn btn-primary btn-block" ng-click="save()">Save Banner</button> 

    </div> 

それは以下のように例外がスローされます:私はエラーを取得する理由

TypeError: BannerService.saveBanner is not a function 
at ChildScope.$scope.save (bannerControllers.js:64) 
at fn (eval at compile (angular.js:13145), <anonymous>:4:203) 
at callback (angular.js:23298) 
at ChildScope.$eval (angular.js:15846) 
at ChildScope.$apply (angular.js:15945) 
at HTMLButtonElement.<anonymous> (angular.js:23303) 
at HTMLButtonElement.dispatch (jquery.js:4435) 
at HTMLButtonElement.elemData.handle (jquery.js:4121) 

誰かが私を助けることができます。大変感謝しています。

答えて

4

はエラーメッセージを見てみましょう:

BannerService.saveBanner is not a function 

は基本的に、あなたのアプリケーションは、プロパティを探しているsaveBannerあなたのサービスに割り当てられています。しかし、現在あなたはそのような財産を宣言していません。サービスには、saveという名前のプロパティ(saveBanner)が定義されています。

AngularJSはプロパティに割り当てられた名前付き関数を気にしません。だから代わりに、あなたはpropertyname自体を調整しなければなりません。したがって、あなたのサービスの機能/プロパティは、このようになります。

this.saveBanner = function() { ... } 
+0

ありがとうございました。 –

+0

うれしい私は助けることができます。正しい答えとしてマークを付けることはいいですね。 :) – Aer0

0

以下のようにサービスを書く。

var self = this; 
self.saveBanner = function() { ... } 
0

コントローラ内の保存機能は実際にあなたのサービスで機能を呼び出すわけではありません。

app.service('BannerService',function ($http) { 
     return { 
      saveBanner: function(banner) { 
       return $http({ 
         method: 'POST', 
         url: 'http://localhost:8081/api/banners' 
        }); 
        } 
       } 
}); 
関連する問題