Pass resolve to body controller - angularjs

Hello ive got something like this
<body ng-app="app" id="ng-app" ng-controller="MasterCtrl">
and some views which need master controller to resolve some data
<div ui-view></div>
im using ui-router
how to pass resolve to masterctrl?
if i try something like doing the master state at '/' in state configuration i dont get master resolved when urling to children

So, you're resolving something in your controller(s).. [let's use 'user']
.state('myCoolState', {
url: baseURL + 'coolState/:id',
templateUrl: baseURL + 'Scripts/Templates/CoolStateView.html',
controller: 'coolStateController',
title: 'MyCoolState.com',
resolve: {
user : function (userService) {
return userService.getUser();
}
}
})
and it's working great.. but now you want to resolve user in your master controller..
What works for me is, with a factory like:
.factory("userService", function ($q, $http, baseURL) {
return {
getUser: function () {
var deferred = $q.defer();
$http({
url: baseURL + 'api/User/',
method: "GET"
})
.then(function (result) {
deferred.resolve(result.data.data);
});
return deferred.promise;
}
}
});
I just inject my userService into the master controller
MasterCtrl.$inject = ['$scope', '$location', '$rootScope', '$state', '$http', 'baseURL', 'userService'];
with my master controller defined as
var MasterCtrl = function ($scope, $location, $rootScope, $state, $http, baseURL, user) {
user.getUser().then(function() {
//stuff where you need access to user
//this won't happen until 'user' is resolved
});
};
It'd be nice to resolve user outside of the masterCtrl definition.. so it looked cleaner.. as far as I know you can't do that.

Related

angular function call before html view is load

I am working on angularjs (1.6) and want to made a functionality in angular service, its call when a controller call and its service have an ajax code like
app.service('myServ', function($http, $window){
this.backdoor=function(){
$http({
method : 'get',
url : 'web_services/backdoor.php'
}).then(function(res){
// console.log(res.data);
// console.log(res.data.length);
if(res.data.length==0)
{
$window.location.href="index.html";
}
});
}});
and my controller code is :
app.controller('myCtrl', function($scope, $http, $window, myServ, $routeParams){
myServ.backdoor();
});
so the above code (service) is check a user session is created or not, but the problem is when session is not created on server side then my html page load for a second then server will call $window.location.href so please help me about the right way to do this....
I believe you need a resolve in angular.config. Its job is to run some code before you are being redirected to your route/state (for ngRoute or ui.router).
To do that you would need to have:
app.service('myServ', function($http, $window){
this.backdoor=function(){
return $http({ // return the promise if you need to use the values in the controller
method : 'get',
url : 'web_services/backdoor.php'
}).then(function(res){
if(res.data.length==0){ $window.location.href="index.html"; }
else{ return res.data; } // return the values
});
}});
and main part:
app.config(['$routeProvider', function($routeProvider) {
$routeProvider
.when('/your_page/:route_params', {
templateUrl: 'your_page_partial.html',
controller: 'myCtrl',
resolve: {
resolvedVal: function resMyService(myServ, $routeParams){ // setting an injectable instance `resolvedVal`
/* use $routeParams values as parameters? */
return myServ.backdoor(); // calling your service
}
}}
);
}]);
Then it's enough to just inject your resolve into the controller:
app.controller('myCtrl', function($scope, $http, $window, resolvedVal){ // note: resolvedVal injection
$scope.my_data = resolvedVal;
});

Angular route not firing at all

I triggered the %a{"ng-click"=>"get_destinations(city)"}
However, it should redirect me to "destinations" controller, but it didn't
and there is no error in webconsole, what's going on ?
welcome.js.erb
var App = angular.module('App', ['ngRoute']);
App.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/depart_from/:id',
{
templateUrl: "<%= asset_path('promotion_destinations.html') %> ",
controller: 'destinations'
}
)
.otherwise({ redirectTo: '/depart_from/:id' });
}]);
App.controller("departure_cities", function($scope, $location, $http) {
$http.get("/promotion.json")
.success(function (response) {
$scope.departure_cities = response;
});
$scope.get_destinations = function(id) {
return $location.url("/depart_from/" + id);
};
});
App.controller("destinations", function($scope, $location, $http) {
$http.get("/another_city.json")
.success(function (response) {
$scope.destinations = response;
});
});
Your default controller is destinations in the $scope of destinations controller no any method like get_destinations .
Put your method in side destinations controller it will work if every thing is fine.
Well if you can link the html generated (the one that see the browser, not the server template) that would help.
However i still see an error for me in the HTML (or it's a naming problem)
get_destinations(city)
And in the javascript :
$scope.get_destinations = function(id)
Maybe you wanted to do this ?
get_destinations(city.id)

How to pass param in routeProvider in Angular JS?

I use routeProvider in Angular JS:
.when('/profile/personal', {
templateUrl: 'personal.html',
controller: 'EditProfileController'
})
How I can pass param to controller EditProfileController and here call Ajax method that returns data. This data must be display in template of route in personal.html.
Example:
.controller('EditProfileController', ['$scope', '$http', function ($scope, $http) {
// If was click on `/profile/personal` from route, must get patam `personal` and call method GetAjax(param);
$scope.GetAjax = function (param){
//here return data put it in template HTML from route
}
}]);
My links are located in page by path:
http://wd.tk/profile
When I click to link route I get URL:
http://wd.tk/profile#/profile/personal/1
Id do:
.controller('EditProfileController', ['$scope', '$http', function ($scope, $http, $routeParams) {
console.log($routeParams);
}]);
I get error:
TypeError: Cannot read property 'idProfile' of undefined
First, in your url configuration, you must put the parameter of url:
when('/profile/personal/:idProfile', {
templateUrl: 'personal.html',
controller: 'EditProfileController'
})
Now, in your EditProfileController, you should get the parameter and call to ajax request:
Inject the $routeParams object and get the parameter with
$routeParams.idProfile:
.controller('EditProfileController',
function ($scope, $http, $routeParams) {
var idProfile = $routeParams.idProfile;
$http.get("service url").then(setData, setError);
function setData(data) {
$scope.data = data;
}
function setError() {
alert("error on get data profile");
}
}]);
In your html, you will show your data profile in the correct format.
But I recommend that all the ajax calls should groups in angular services.
PD:
Check It out angular ui router:
What is the difference between angular-route and angular-ui-router?
hope this helps.
You you need to change your $routeProvider, that should have /profile/:type instead of /profile/personal that means you are going to provide value for :type which can be accessible by injectin $routeParams service inside controller.
.when('/profile/:type', {
templateUrl: 'personal.html',
controller: 'EditProfileController'
})
Controller
.controller('EditProfileController', ['$scope', '$http', '$routeParams', function ($scope, $http, $routeParams) {
$scope.profileType = $routeParams.type;
$scope.GetAjax = function (){
//here you have profile type in $scope.profileType
//you can pass it to ajax by simply accessing scope variable.
$http.get('/getprofiledata?type='+ $scope.profileType)
.success(function(data){
$scope.profileData = data;
})
.error(function(error){
console.log('error occured')
})
}
$scope.GetAjax(); //calling it on controller init
}]);
Update
YOu had missed one of dependency $routeParams in array annotation.
.controller('EditProfileController', ['$scope', '$http', '$routeParams',function ($scope, $http, $routeParams) {
console.log($routeParams);
}]);

Changing route with ui-router skipping resolve

I am using ui-router in my angular app.
I define the routing like this:
angular.module('app.product', [])
.config(['$stateProvider', function($stateProvider) {
$stateProvider
.state('product', {
url: '/product/:product_id',
templateUrl: 'partial/product',
controller: 'productCtrl',
resolve: {
product: ['$http', '$stateParams',
function($http, $stateParams) {
return $http.get('/api/product/' + $stateParams.product_id);
}]
}
})
}])
At some point, I manually change the route on the client side using $state.go('product'). Here I already have the product data on the client side so there is no need for an extra $http request.
What is the best way to pass the data in the $state.go call and let ui-router know there is no need to make this request?
Should I build a service to handle this?
Use a service (something like the code below). Just note this is off the top of my head.
.config(['$stateProvider', function($stateProvider) {
$stateProvider
.state('product', {
url: '/product/:product_id',
templateUrl: 'partial/product',
controller: 'productCtrl',
resolve: {
product: ['ProductCache', '$stateParams',
function(ProductCache, $stateParams) {
return ProductCache.getProduct($stateParams.product_id);
}]
}
});
}])
.factory('ProductCache', ['$http', '$q', function($http, $q) {
var cache = [];
return {
getProduct: function(id) {
// return the product if available, otherwise from the api
if(!cache[id]){
return $http.get('/api/product/' + id, function(result){
cache[id] = result.product; // or however your api return is structured
return cache[id];
});
}else{
// use .when() to ensure a promise is returned to the resolve function
return $q.when(cache[id]);
}
}
};
}]);

Using resolve in $routeProvider causes 'Unknown provider ...'

I am trying to do an asynchronous http request to load some data before my app loads and so I am using a resolve in $routeProvider which is an http request in my MainController. For some reason, I keep getting Error: [$injector:unpr] Unknown provider: appDataProvider <- appData where appData is where I do my http request. I am using AngularJS v 1.2.5.
Here is the code and two methods that I tried that both give the same error:
Method #1
MainController.js
var MainController = ['$scope','$location','appData',
function($scope, $location, appData){
console.log(appData.data);
}
];
MainController.loadData = {
appData: function($http, $location, MainFactory){
var aid = MainFactory.extractAid($location);
return $http({method: 'GET', url: URL_CONST + aid});
}
};
app.js
var app = angular.module('HAY', ['ngRoute']);
app.config(function($routeProvider) {
$routeProvider
.when('/', {
redirectTo: '/pages/alerts'
})
.when('/pages/:pageName', {
templateUrl: function(params) {
return 'views/pages/' + params.pageName + '.html';
},
controller: MainController,
resolve: MainController.loadData
})
.otherwise({
redirectTo: '/pages/alerts'
});
});
I tried changing the name in case it was a conflicting system reserved keyword but with no luck. For some reason, appData is never recognized
Method #2
I also tried changing it around like so:
app.js
var app = angular.module('HEY', ['ngRoute']);
app.config(function($routeProvider) {
$routeProvider
.when('/', {
redirectTo: '/pages/alerts'
})
.when('/pages/:pageName', {
templateUrl: function(params) {
return 'views/pages/' + params.pageName + '.html';
},
controller: MainController,
resolve: {
appData: ['$http', '$location','MainFactory', function($http, $location, MainFactory) {
var aid = MainFactory.extractAid($location);
return $http({method: 'GET', url: URL_CONST + aid});
}]
}
})
.otherwise({
redirectTo: '/pages/alerts'
});
});
MainController.js
var MainController = ['$scope','$location','appData',
function($scope, $location, appData){
console.log(resolvedData);
}
];
However, the result was exactly the same. Does this have something to do with angular 1.2.5 ?
Here is a working version from someone else
http://mhevery.github.io/angular-phonecat/app/#/phones
And here is the code:
function PhoneListCtrl($scope, phones) {
$scope.phones = phones;
$scope.orderProp = 'age';
}
PhoneListCtrl.resolve = {
phones: function(Phone) {
return Phone.query();
},
delay: function($q, $defer) {
var delay = $q.defer();
$defer(delay.resolve, 1000);
return delay.promise;
}
}
angular.module('phonecat', ['phonecatFilters', 'phonecatServices', 'phonecatDirectives']).
config(['$routeProvider', function($routeProvider) {
$routeProvider.
when('/phones', {templateUrl: 'partials/phone-list.html', controller: PhoneListCtrl, resolve: PhoneListCtrl.resolve}).
otherwise({redirectTo: '/phones'});
}]);
Here's an example of the code I've used in the application I'm working on, not sure it will help much because its not much different than how you have it already.
Routing
.when('/view/proposal/:id',{
controller : 'viewProposalCtrl',
templateURL : 'tmpls/get/proposal/view',
resolve : viewProposalCtrl.resolveViewProposal
})
Controller
var viewProposalCtrl = angular.module('proposal.controllers')
.controller('viewProposalCtrl',['$scope','contacts','details','rationale',
function($scope,contacts,details,rationale){
$scope.contacts = contacts;
$scope.details = details;
$scope.rationale = rationale;
// [ REST OF CONTROLLER CODE ]
});
// proposalSrv is a factory service
viewProposalCtrl.resolveViewProposal = {
contacts : ['$route','proposalSrv',function($route,proposalSrv){
return proposalSrv.get('Contacts',$route.current.params.id)
.then(function(data){
return data.data.contacts;
},function(){
return [];
});
}],
details : ['$route','proposalSrv',function($route,proposalSrv){
return proposalSrv.get('Details',$route.current.params.id)
.then(function(data){
return data.data.details;
},function(){
return {};
});
}],
rationale : ['$route','proposalSrv',function($route,proposalSrv){
return proposalSrv.get('Rationale',$route.current.params.id)
.then(function(data){
return data.data.rationale;
},function(){
return {};
]
}]
};
Now that I think about it, when I was developing my application I did have a problem and not sure why when I named my resolve function "resolve." This gave me a problem:
.when('/path',{
// stuff here
resolve : myCtrlr.resolve
})
but this did not:
.when('/path',{
//stuff here
resolve : myCtrlr.myResolveFn
})
Another Possibility
The only other thing I can think of, is that you're returning the promise from the $http call and then trying to use appData.data Try using the .then function or one of the other functions (.success,.error) to retrieve the information from the promise.
The problem was NOT due to previously using different version of AngularJS.
Here are the fixes using the code that I have above.
In app.js, you need to declare the controller as controller: 'MainController' and NOT as controller: MainController even though you have var MainController = app.controller('MainController', ....).
Second and biggest thing was that in my index.html I declared my controller already like so:
index.html
body ng-app="HEY" controller="MainController" /body
This was causing the whole Unknown provider error Apparently angular wont tell you that you have already declared the controller that you are using to do the resolve it and that that will cause a weird error that have nothing to do with the resolve.
I hope this helps someone who may have the same problem.
One thing I noticed in angular 1x docs is that YOU DO NOT SPECIFY THE RESOLVED PARAMETER AS AN ANNOTATED DEPENDENCY
So this:
.when('/somewhere', {
template: '<some-component></some-component>',
resolve: {
resolvedFromRouter: () => someService.fetch()
}
})
export default [
'$scope',
'someService',
'resolvedFromRouter'
Controller
]
function Controller($scope, someService, resolvedFromRouter) {
// <= unknown provider "resolvedFromRouter"
}
is wrong. You don't specify the resolved parameter as a dependency, in the docs:
For easier access to the resolved dependencies from the template, the resolve map will be available on the scope of the route, under $resolve (by default) or a custom name specified by the resolveAs property (see below). This can be particularly useful, when working with components as route templates.
So just do this instead:
.when('/somewhere', {
template: '<some-component></some-component>',
resolve: {
resolvedFromRouter: () => someService.fetch()
}
})
export default [
'$scope',
'someService',
Controller
]
function Controller($scope, someService) {
$scope.$resolve.resolvedFromRouter; // <= injected here
}

Resources