私のangularJsアプリでは、コントローラで$ routeParamsを取得できますが、サービスでどのように取得する必要がありますか?私は心配のアプローチの分離に従って、私のHTTP要求を私のコントローラとは別にしておきたいと思います。
私は私のapp.js
に下記試みたが、私はすべてのError: $injector:unpr Unknown Provider
var app = angular.module('app', ['ngRoute']); // TODO: 'ngAnimate', 'ui.bootstrap'
app.config(['$routeProvider','$locationProvider', function($routeProvider, $locationProvider){
$routeProvider
.when('/', {
templateUrl: '/app/static/home.html',
controller: 'mainController as mainCtrl'
})
.when('/match/id-:matchId', {
templateUrl: '/app/components/match/matchView.html',
controller: 'matchController as matchCtrl'
});
// use the HTML5 History API
$locationProvider.html5Mode(true);
}]);
app.controller('matchController', ['$routeParams', 'matchService', function ($routeParams, matchService) {
var matchCtrl = this;
matchCtrl.matchId = $routeParams..matchId; // how can I move this into the service
this.getMatchId = function()
{
return matchCtrl.matchId;
};
var promise = matchService.getMatch();
promise.then(function (data)
{
matchCtrl.match = data;
});
}])
app.service("matchService", function ($http, $q, matchController)
{
var matchId = matchController.getTable();
var url = 'https://jsonplaceholder.typicode.com/posts/1';
$http({
method: 'GET',
cache: true,
url: url,
headers: {
'Content-Type': 'application/json;charset=UTF-8'
}
}).
success(function(response) {
//your code when success
// lgTblCtrl.amateurTable = data;
deferred.resolve(response);
console.log('SUCCESS!');
}).
error(function(response) {
//your code when fails
console.log('ERROR!');
});
this.getTable = function()
{
return deferred.promise;
};
})
ありがとうございますが、私はまだあなたが上に置いたもので働くことができません。コンソールにエラーはありませんが、Chromeソースパネルにブレークポイントを置くと、 'promise'や' deferred'ステートメントの前に 'this.getMatch = getMatch'が壊れています。 'deferred.resolve(応答);で破損したとき'応答 'のデータを見ることができますが、 'matchCtrl.match = data'で渡されません – Holly
私はサンプルアプリケーションを作成し、 。 – Aruna
https://gist.github.com/anonymous/8c8eeec87d3b40bdbcae7c640a82ab81で作業していますが、それはうまくいくようです。あなたが答えにそれを追加/含めると、それを正しいものとしてマークします。あなたの助けをありがとうございます:) – Holly