I am trying to use a resolve to front-load data from Rates Service in my Controller (rates controller) and get a blank screen. The api works but for some reason when I go step by step, in the execution, it skips over the $http.get method within the service :-/. Does anyone have any suggestions on how to fix this? Cheers!
rates.contoller.js
(function () {
'use strict';
angular.module('print.module').controller('ratesCtrl', ['ratesTest123', function (ratesTest123) {
console.log(ratesTest123);
}]
)})();
rates.service.js
(function () {
'use strict';
angular.module('print.module').service('ratesService', ['$http', function ($http) {
vm = this;
function getRatesDataService() {
console.log("test");
return this.$http.get("api/Rates/GetRates");
}
//}
}]
)
})();
print.module.js
(function () {
"use strict";
var module = angular.module('print.module', [
'ui.router',
]);
module.config(function ($stateProvider, $urlRouterProvider, $locationProvider) {
$urlRouterProvider.otherwise('/print');
$stateProvider
.state('print', {
url: '/print',
templateUrl: "Public/scripts/sharedViews/printNavbar.html"
})
.state('print.rates', {
url: "/rates",
controller: 'ratesCtrl',
templateUrl: "Public/scripts/rates/rates.view.html",
controllerAs: 'vm',
resolve: {
ratesTest123: ['ratesService', '$q', function (ratesService, $q) {
var deferred = $q.defer();
ratesService.getRatesDataService().then(function (response) {
deferred.resolve(response.data);
});
return deferred.promise;
}]
}
})
$locationProvider.html5Mode(true);
});
}());
view (scripts tags only for reference)
<body ng-app="print.module">
<div ui-view></div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.3.1/angular-ui-router.min.js"></script>
<script type="text/javascript" src="~/public/scripts/print.module.js"></script>
<script type="text/javascript" src="~/public/scripts/books/books.controller.js"></script>
<script type="text/javascript" src="~/public/scripts/terms/terms.controller.js"></script>
<script type="text/javascript" src="~/public/scripts/rates/rates.service.js"></script>
<script type="text/javascript" src="~/public/scripts/rates/rates.controller.js"></script>
<script type="text/javascript" src="~/public/scripts/services/modals.service.js"></script>
</body>
Assign the getRatesDataService function to your service
(function () {
'use strict';
angular.module('print.module').service('ratesService', ['$http', function ($http) {
this.getRatesDataService = function () {
console.log("test");
return $http.get("api/Rates/GetRates");
}
//}
}]
)
} )();
since it returns a promise, you can simply do the following
resolve: {
ratesTest123: ['ratesService', function (ratesService) {
return ratesService.getRatesDataService()
}]
}
Related
I'm working with symfony and AngularJs 1.6.8 and Symfony 3.4. I have the next configuration:
base.html.twig
<html lang="en" data-ng-app="CeocApp" ng-controller="CeocController">
//css for the app
<link id="ng_load_plugins_before"/>
//more ccs for the app
<body>
....
<div class="row" ui-view></div>
....
<script src="{{ asset('assets/angular/angular/angular.min.js') }}" type="text/javascript"></script>
<script src="{{ asset('assets/angular/angular-sanitize/angular-sanitize.min.js') }}" type="text/javascript"></script>
<script src="{{ asset('assets/angular/angular-touch/angular-touch.min.js') }}" type="text/javascript"></script>
<script src="{{ asset('assets/angular/angular-ui-router/release/angular-ui-router.min.js') }}"
type="text/javascript"></script>
<script src="{{ asset('assets/angular/oclazyload/dist/ocLazyLoad.min.js') }}" type="text/javascript"></script>
<script src="{{ asset('assets/angular/angular-ui-bootstrap/dist/ui-bootstrap-tpls.js') }}"
type="text/javascript"></script>
<script src="{{ asset('assets/ceoc/angular_app/ceoc-angular-app.js') }}"></script>
</body>
</html>
ceoc-app.js
var CeocApp = angular.module('CeocApp', [
'ui.router',
"ui.bootstrap",
"oc.lazyLoad",
"ngSanitize"
]).config(['$interpolateProvider', function ($interpolateProvider) {
$interpolateProvider.startSymbol('{[{').endSymbol('}]}');
}]);
CeocApp.config(['$stateProvider', '$urlRouterProvider', function ($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise("/dashboard");
$stateProvider
.state('dashboard', {
url: "/dashboard",
templateUrl: "../templates/dashboard.html",
controller: "DashboardController as dashboard",
resolve: {
deps: ['$ocLazyLoad', function ($ocLazyLoad) {
return $ocLazyLoad.load({
name: 'CeocApp',
insertBefore: '#ng_load_plugins_before',
files: [
'../assets/ceoc/angular_app/controllers/dashboard-controller.js'
]
});
}]
}
})
}]);
dashboard-controller.js is a controller that works but there are the problems:
Problem 1:$http.get(Rountin.generate('route_name')) doesn't work.
When I run the app the controller is loaded and all before that $http.get() request works but the code after that doesn't()
angular.module('CeocApp').controller('DashboardController', ['$scope', '$rootScope', function ($scope, $rootScope, $http) {
$rootScope.pageTitle = 'Dashboard';
$scope.total = 2500;
alert('this line will be reached');
$http.get(Routing.generate('ceoc.dashboard')).then(function (data) {
$scope.total = 10000
}, function (data) {
});
alert('this line will never be reached');
}]);
Problem 2: $.get doesn't let me change the $scope value.
When I change $http.get() for $.get() it works and the ajax request is made but the $scope.total value is not modified.
angular.module('CeocApp').controller('DashboardController', ['$scope', '$rootScope', function ($scope, $rootScope, $http) {
$rootScope.pageTitle = 'Dashboard';
$scope.total = 2500;
$.get(Routing.generate('ceoc.dashboard')).success(function (data) {
alert('request successfull');
$scope.total = 200; //this value won't be setted
}).then(function () {
$scope.total = 6000;
});
$scope.total = '879';//this value will be setted
}]);
The server response
{"retrasadas":5,"total":10,"en_tiempo":5}
My question is how can I set properly a $scope.anyvar value after a successfull ajax request? (with $ or $http)
Am I missing something?
Thanks in advance
Using Coec's handleAjax function and it's callback parameter:
Ceoc.handleAjax(Routing.generate('ceoc.dashboard'), "GET", function (data) {
$scope.total = data.total;
$scope.$apply();
});
First time doing an angular application, combining different tutorials but this is the first time I am trying to inject a service.
I have one of my View's controllers like:
angular.module("myApp.Pages").controller('signupController', ['$scope', '$location', '$timeout', 'authService', function ($scope, $location, $timeout, authService) {
}
however am seeing an error when I look at the Console in Developer Tools:
angular.js:12793 Error: [$injector:unpr] Unknown provider:
authServiceProvider <- authService <- signupController
http://errors.angularjs.org/1.5.0-beta.2/$injector/unpr?p0=authServiceProvider%20%3C-%20authService%20%3C-ignupController
My project structure is:
-Client
-App
-Components
-Services
-authService.js
-myAppCore.js
-Views
-app.js
-appRouting.js
-Scripts (References)
-Theme (Css)
-Index.html
My index.html scripts I add:
<!-- Angular References-->
<script src="References/Angular/angular.js"></script>
<script src="References/Angular/angular-route.js"></script>
<script src="References/Angular/angular-ui-router.min.js"></script>
<!-- End Angular References-->
<!-- my app and dependent modules -->
<script src="App/app.js"></script>
<script src="App/appRouting.js"></script>
<!-- Services -->
<script src="App/Components/Services/authService.js"></script>
<!-- END services-->
<!-- Controllers for your pages-->
<script src="App/Pages/Home/homeController.js"></script>
<script src="App/Pages/ContactUs/contactusController.js"></script>
<script src="App/Pages/Entry/entryController.js"></script>
<script src="App/Pages/Signup/signupController.js"></script>
<!-- End Controllers for the page-->
My app.js
angular.module("myApp", [
// User defined modules
'myApp.Templates', // templates
'myApp.Pages', // Pages
'myApp.Core', // Core
// Angular modules
'ui.router', // state routing
'ngRoute', // angular routing
'angular-loading-bar', //loading bar
'LocalStorageModule', //local browser storage
])
and appRouting.js
angular.module("myApp")
.config(["$stateProvider", function ($stateProvider) {
$stateProvider.state('Home', {
url: '/Home',
templateUrl: 'App/Pages/Home/home.html',
controller: 'homeController'
})
.state('Entry', {
url: '/Entry',
templateUrl: 'App/Pages/Entry/entry.html',
controller: 'entryController'
})
.state('Signup', {
url: '/Signup',
templateUrl: 'App/Pages/Signup/signup.html',
controller: 'signupController'
})
.state('Contactus', {
url: '/Contactus',
templateUrl: 'App/Pages/ContactUs/contactus.html',
controller: 'contactusController'
})
.state("otherwise", {
url: "*path",
templateUrl: "App/Pages/NotFound/notFound.html"
});
}])
.run(["$location", function ($location) {
// Go to state dashboard
$location.url('/Home');
}]);
authService which handles login/register:
app.factory('authService', ['$http', '$q', 'localStorageService', function ($http, $q, localStorageService) {
var serviceBase = '<location>';
var authServiceFactory = {};
var _authentication = {
isAuth: false,
userName: ""
};
var _saveRegistration = function (registration) {
_logOut();
return $http.post(serviceBase + 'api/account/register', registration).then(function (response) {
return response;
});
};
var _login = function (loginData) {
var data = "grant_type=password&username=" + loginData.userName + "&password=" + loginData.password;
var deferred = $q.defer();
$http.post(serviceBase + 'token', data, { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }).success(function (response) {
localStorageService.set('authorizationData', { token: response.access_token, userName: loginData.userName });
_authentication.isAuth = true;
_authentication.userName = loginData.userName;
deferred.resolve(response);
}).error(function (err, status) {
_logOut();
deferred.reject(err);
});
return deferred.promise;
};
var _logOut = function () {
localStorageService.remove('authorizationData');
_authentication.isAuth = false;
_authentication.userName = "";
};
var _fillAuthData = function () {
var authData = localStorageService.get('authorizationData');
if (authData) {
_authentication.isAuth = true;
_authentication.userName = authData.userName;
}
}
authServiceFactory.saveRegistration = _saveRegistration;
authServiceFactory.login = _login;
authServiceFactory.logOut = _logOut;
authServiceFactory.fillAuthData = _fillAuthData;
authServiceFactory.authentication = _authentication;
return authServiceFactory;
}]);
myAppPages.js and myAppCore.js are the same just their respective names :
angular.module("myApp.Pages", []);
Edit: Seeing a "app is not defined" reference error in authService
You don't defined var app, so use angular.module("myApp") to define your factory
angular.module("myApp").factory('authService', ['$http', '$q', 'localStorageService', function ($http, $q, localStorageService)
Also you can declare var app = angular.module("myApp") and use app
I simply did not declare:
var app = angular.module(...)
And my service was referencing app when that did not exist.
var myApp = angular.module("MyApp", ['ngRoute']);
myApp.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/', {
templateUrl: 'partials/cart.php',
controller: 'ctrl',
resolve: {
categories: function(cartService){
console.log('inside resolve categories')
return cartService.getCategories();
}
}
}).
otherwise({
redirectTo: '/'
});
}]);
myApp.controller('ctrl', function (categories, $scope) {
$scope.items = categories;
});
myApp.service("cartService", function ($http, $q) {
this.getCategories = function () {
var deferred = $q.defer();
$http.get('js/categories.js')
.then(function (response) {
deferred.resolve(response.data);
});
return deferred.promise;
}
});
myApp.run(['$rootScope',function($rootScope){
$rootScope.stateIsLoading = false;
$rootScope.$on('$routeChangeStart', function(e, current, pre) {
$rootScope.stateIsLoading = true;
var fullRoute = current.$$route.originalPath;
if(fullRoute == '/')
{
console.log('load categoreis and products')
}
});
$rootScope.$on('$routeChangeSuccess', function() {
$rootScope.stateIsLoading = false;
console.log('route changed');
});
$rootScope.$on('$routeChangeError', function() {
//catch error
});
}]);
I have placed the ng-app and ng-controller directives at the top of the HTML
<html lang="en" ng-app="MyApp" ng-controller="ctrl">
But when I run the HTML I get the following error
Error: [$injector:unpr] Unknown provider: categoriesProvider <-
categories <- ctrl
How can I fix this ?
Edit: If I remove ng-controller="ctrl" from the HTML, then no errors
You got that error just because, you are using the same controller for both index.php and 'partials/cart.php'
Create a separate controller for 'partials/cart.php' to resolve this
problem
Code Snippet:
// Code goes here
var app = angular.module('app', ['ngRoute']);
app.controller('indexCtrl', function($scope) {
$scope.title = 'Header';
});
app.config(function($routeProvider) {
$routeProvider.when('/', {
template: "<ul><li ng-repeat='item in items'>{{item}}</li></ul>",
controller: 'categoryCtrl',
resolve: {
categories: function(cartService){
return cartService.getCategories();
}
}
});
});
app.controller('categoryCtrl', function (categories, $scope) {
$scope.items = categories;
});
app.service("cartService", function() {
this.getCategories = function() {
return ['A', 'B', 'C'];
};
});
<html ng-app="app">
<head>
<script data-require="angular.js#1.4.9" data-semver="1.4.9" src="https://code.angularjs.org/1.4.9/angular.js"></script>
<script data-require="angular-route#1.4.2" data-semver="1.4.2" src="https://code.angularjs.org/1.4.2/angular-route.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body ng-controller="indexCtrl">
<h1>{{title}}</h1>
<div ng-view></div>
</body>
</html>
you have to define the categories service/factory which is injected in your controller 'ctrl'.
So i still new to angular and java script but i read it was good practical to wrap the everything into functions.
This is what i have done.
in comment is the previous version
app.js
//var app = angular.module('app',['ngRoute','ngResource','routes']);
(function(angular) {
angular.module("app.directives", []);
angular.module("app.controllers", []);
angular.module("app", ['ngRoute','ngResource','routes','app.directives','app.controllers']);
}(angular));
directives.js
/*
app.directive('footer', function () {
return {
replace: true,
templateUrl: "/template/main_footer.html",
controller: ['$scope', '$filter', function ($scope, $filter) {
}]
}
});
*/
(function(angular) {
var footer = function () {
return {
replace: true,
templateUrl: "/template/main_footer.html",
controller: ['$scope', '$filter', function ($scope, $filter) {
}]
};
};
footer.$inject = [];
angular.module("app.directives").controller("footer", footer);
});
controller.js
/*app.controller('HeaderController',function($scope, $location) {
$scope.isActive = function (viewLocation) {
var active = (viewLocation === $location.path());
return active;
};
});*/
(function(angular) {
var HeaderController = function($scope,$location){
$scope.isActive = function(viewLocation){
var active = (viewLocation === $location.path());
return active;
};
}
HeaderController.$inject = ['$scope','$location'];
angular.module("app.controllers").controller("HeaderController", HeaderController);
})
and how should i proceed for routes.js
angular.module('routes', []).config(function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'pages/home.html'
})
.when('/second', {
templateUrl: 'pages/second.html'
})
.when('/third', {
templateUrl: 'pages/third.html'
})
.when('/123', {
templateUrl: 'pages/123.html'
})
.otherwise({
redirectTo: '/'
});
});
index.html
<!DOCTYPE html>
<html ng-app="app">
<head>
<link rel="stylesheet" href="css/bootstrap.min.css">
<link rel="stylesheet" href="css/custom.css">
<script type="text/javascript" src="https://code.angularjs.org/1.4.4/angular.js"></script>
<script type="text/javascript" src="https://code.angularjs.org/1.4.4/angular-resource.js"></script>
<script type="text/javascript" src="https://code.angularjs.org/1.4.4/angular-route.js"></script>
<script type="text/javascript" src="js/routes.js"></script>
<script type="text/javascript" src="js/app.js"></script>
<script type="text/javascript" src="js/controllers.js"></script>
<script type="text/javascript" src="js/directives.js"></script>
</head>
<body>
<div ng-view></div>
</body>
</html>
But it does not work. And i find it hard to find what went wrong because i don't get a error with the development tools on google chrome
Update
Now i do call the function at the end.
But i still can't see the footer. I also added the footer.html just in case there would something i forgot there.
directives.js
(function(angular) {
var footer = function () {
return {
replace: true,
templateUrl: "/template/main_footer.html",
controller: ['$scope', '$filter', function ($scope, $filter) {
}]
};
};
footer.$inject = [];
angular.module("app.directives").controller("footer", footer);
}(angular));
home.html
<div>
<div>
<h3>This is the homepage</h3>
</div>
<div footer></div>
</div>
In the 'directives.js' and 'controller.js' files, you forgot (angular) at the end, like in 'app.js'.
If you write a function like this:
function f() {
// do stuff...
}
it's never going to run unless you call it somewhere: f();. Now, if you want to wrap a bit of code in a function, you still want it to run immediately as if it had not been wrapped. So what you do is you call the wrapping function immediately like this:
(function f() {
// do stuff...
})();
or like this (same thing):
(function f() {
// do stuff...
}());
In that second way of writing things, the outermost parentheses are useless for the program but they help the reader see that the function will be immediately run (or "evaluated", or "called").
You can also pass anything that lives outside of the function into the function, for example angular:
(function f(angular) {
// do stuff...
}(angular));
That is because you're missing the function invocation in some of those wrappings. For example, controller.js needs to be:
(function(angular) {
var HeaderController = function($scope,$location){
$scope.isActive = function(viewLocation){
var active = (viewLocation === $location.path());
return active;
};
}
HeaderController.$inject = ['$scope','$location'];
angular.module("app.controllers").controller("HeaderController", HeaderController);
})(angular); // CALL FUNCTION
Note in the last line I added (angular); to actually call the function.
Here is the sample (from Angular official site):
angular.module('project', ['ngRoute', 'firebase']).
value('fbURL', 'https://angularjs-projects.firebaseio.com/').
factory('Projects', function(angularFireCollection, fbURL) {
return angularFireCollection(fbURL);
}).
config(function($routeProvider) {
$routeProvider.
when('/', {controller:ListCtrl, templateUrl:'list.html'}).
when('/edit/:projectId', {controller:EditCtrl, templateUrl:'detail.html'}).
when('/new', {controller:CreateCtrl, templateUrl:'detail.html'}).
otherwise({redirectTo:'/'});
});
function ListCtrl($scope, Projects) {
$scope.projects = Projects;
}
function CreateCtrl($scope, $location, $timeout, Projects) {
$scope.save = function() {
Projects.add($scope.project, function() {
$timeout(function() { $location.path('/'); });
});
}
}
function EditCtrl($scope, $location, $routeParams, angularFire, fbURL) {
angularFire(fbURL + $routeParams.projectId, $scope, 'remote', {}).
then(function() {
$scope.project = angular.copy($scope.remote);
$scope.project.$id = $routeParams.projectId;
$scope.isClean = function() {
return angular.equals($scope.remote, $scope.project);
}
$scope.destroy = function() {
$scope.remote = null;
$location.path('/');
};
$scope.save = function() {
$scope.remote = angular.copy($scope.project);
$location.path('/');
};
});
}
Link: http://jsfiddle.net/TE2WR/
Firefox console shows:
[01:45:20.760] Error: [$injector:modulerr] http://errors.angularjs.org/undefined/$injector/modulerr?p0=project&p1=%5B%24injector%[...]
What's going on?
Edit:
My HTML scripts:
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular-resource.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0rc1/angular-route.min.js"></script>
<script src="https://cdn.firebase.com/v0/firebase.js"></script>
<script src="http://firebase.github.io/angularFire/angularFire.js"></script>
Be sure to include ngRoute and firebase scripts so that they are available to inject as dependencies.
For example, include ngRoute like this:
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.min.js"></script>
<script src="http://code.angularjs.org/1.2.0-rc.2/angular-route.min.js"></script>
angular.module('project', ['ngRoute']).
config(function($routeProvider) {
});
You missed angular-route.js and firebase.js and angularfire.js in jsfiddle.
This would work
</style> <!-- Ugly Hack due to jsFiddle issue: http://goo.gl/BUfGZ -->
<link rel="stylesheet" href="http://twitter.github.com/bootstrap/assets/css/bootstrap.css">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular-route.min.js"></script>
<script src="https://cdn.firebase.com/v0/firebase.js"></script>
<script src="https://rawgithub.com/firebase/angularFire/master/angularfire.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular-resource.min.js"></script>
<style>