2016-09-26 5 views
0

私が指定する方法を、私は私の最初のルートを作成し、現在コントローラにどのような指示に書き込むようにして何と戦っヨーマン https://github.com/yeoman/generator-angularAngularJS、私の最初のHTMLコンポーネント「ウィジェット」

と私の最初のAngularJSアプリを生成POSTまたはPUT(私はバックエンドの準備ができています)から受け取ったAPIServiceのJSONメッセージ..

私はyeomanを使って新しいサービスを作成し、コードを拡張しようとしましたが、エラーが表示されます。未定義の 'then'プロパティサービス内のコードは次のとおりです。

angular.module('baApp').service('myService', function ($http, $q) { 

this.getTiers = function(){ 
    $http.get('/data/tiers.json').success(function (data) { 
     console.log('$http tiers'); 
     console.log(data); 
    }); 
}; 
this.getCapabilities = function(){ 
    $http.get('/data/capabilities.json').success(function (data) { 
     console.log('$http capabilities'); 
     console.log(data); 
    }); 
}; 

return this; 
}); 

と、このコントローラーのコード:

angular.module('baApp') 
    .controller('MyappCtrl', function ($scope, myService) { 

    myService.getTiers().then(function(res){ 
    $scope.tiers = res; 
     console.log('Tiers'); 
     console.log(res); 
    }); 

    myService.getCapabilities().then(function(res){ 
     $scope.capabilities = res; 
     console.log('Capabilities'); 
     console.log(capabilities); 
    }); 

}); 
+0

である私は私の質問を編集し、それが – Micky

答えて

1

@Micky、

これはあなたにjsfiddle

を助けるかもしれない、私はいくつかのサンプルを追加しましたあなたがapiからいくつかのダミーデータを必要とする場合は準備が整うまで、jsonを使用してapiの応答を嘲笑することができます。

だから、これはサンプルコード

var app = angular.module('myApp', []); 
app.controller('ctrl',function($scope, myService){ 
myService.getData().then(function(res){ 
    $scope.data = res; 
}); 
}); 
//service here 
app.service('myService', function($http, $q){ 
var responseJson = {'message':'welcome to angular'} 
this.getData = function(){ 
// call api or json file 
// like 
//return $http.get('api url or /test.json'). 

// fake response here 
var deferred = $q.defer(); 
deferred.resolve(responseJson); 
return deferred.promise; 
} 
return this; 
}); 
+0

こんにちはジャヤントを助け、私はhtmlファイル(テンプレート)をリンクする必要が答え..に感謝を願っていますか?私は、テーブルやフォームをテンプレートとして使い、同じ単一ページのhtmlでもう一度それらを再利用して、ウィジェットのように扱いたいと思っています。私は考えています。あなたのコードとエモマンのサポートによって、確信しています:-) – Micky

+0

ありがとう@ジャヤント、しかし私のJSONは埋め込まれています..外部ファイルの変数に格納されています。何か$ http.getの代わりに何をすればいいですか? – Micky

関連する問題