I'm interested in learn angular, is getting so popular it seems necessary to lean something about it.
I'm having an issue, I did a Little application in angular 1.0.x, but in order to extend my knowledge about angular I decide to add a functionality and complexity to my code.
After Reading some blogs I modify my app and update it to angular 1.6. So I'm trying to use a service which provides me the data, till now the data are a fixed JSON, which give me several objects to trat and show in the screen. But I'm having some difficulties, the code I'm trying is next one:
var app = angular.module('myApp', ['ngRoute']);
app.config(appConfig);
app.service('MyService', MyService);
app.controller('TestController', ['$http', TestController])
function appConfig($routeProvider, MyService) {
$routeProvider.when('/', {
templateUrl: './test.html',
controller: 'TestController',
controllerAs: 'my',
resolve: {
data: MyService.getData()
}
});
}
function TestController($http, MyService) {
// some code
}
function MyService() {
return {
getData: getData
}
function getData() {
var datos = [ << valid json >> ];
return datos;
}
}
But it seems I'm injecting wrong the service it says my it's and unknow provider.
If I quit references to the service it works, I have to assign other way the data but it does work without the service. I think I've done everything according to the tutorials I've read, but It's obvious there's something wrong, and as long as I can't identify it Clearly I need someone to explain my the basics of injections in angular.
SO I have questions: How do I inject a service? What am I doing wrong? Why my code is not working?
Finally it worked, now the code looks like this:
var app = angular.module('myApp',['ngRoute']);
app.provider('myProvider', function myProvider(){
this.$get=function(){
return new mFactory();
}
});
app.controller('TestController', TestController);
app.config(appConfig);
TestController.$inject = ['$http', 'myProvider'];
function appConfig($routeProvider){
$routeProvider.when('/', {
templateUrl: './test.html',
controller: 'TestController',
controllerAs: 'my'
});
}
function mFactory(){
return{
getData:function(){
return mydata();//returns some valid json
}
}
}
It was a bit hard for me to understand what a provider is but now i understand a provider has factories and each Factory returns the collections which services produce. Once i get to understand that everything come easier. Thank you all of you for your answers, each one has help me to find the solution to my little experiment. It feels fine to know there's people eager to help. Greetings