I am new in Angular JS and I stack with problem with inject resolve promise to controller.
I have next code:
var app = angular.module('app', ['ui.router', 'ngAnimate', 'ngSanitize', 'ui.bootstrap'])
.config(function ($stateProvider, $urlMatcherFactoryProvider, $urlRouterProvider) {
$urlMatcherFactoryProvider.caseInsensitive(true);
$urlRouterProvider.otherwise('/refuel');
$stateProvider.state('refuels', {
url: '/refuel',
controller: 'refuelController',
controllerAs: 'refuelCtrl',
resolve: {
$refuelsPumpsResolve: function ($http) {
return $http({
url: "http://localhost:60000/Refuels/GetUserPumps",
method: "GET"
})
}
}
})
})
.controller('refuelController', function ($refuelsPumpsResolve) {
var $this = this;
this.isOpen = true;
this.isOpen = function () {
$this.isOpen = !$this.isOpen
}
this.pumpsData = $refuelsPumpsResolve;
});
However angular throws 'Unknown provider' exception for $refuelsPumpsResolve in controller.
I do not see any problem, more over the code was taken from ui-route tutorial on github.
Thanks for help
Try this, declaring the injection as you would normally do for say, a controller:
resolve: {
$refuelsPumpsResolve: ['$http', function ($http) {
return $http({
url: "http://localhost:60000/Refuels/GetUserPumps",
method: "GET"
})
}]
}
Related
So i am trying to pass the promise from a http request to a resolve which would then only when received load a view. I am wondering where the mistake is here as i get a Uncaught Error: [$injector:modulerr] error. The "mainsearch" controller is the controller where state.go is defined and not the controller for the template. I am not sure if that causes an issue.
//in app.js
.state({
name: "mainSearch",
url: "/mainSearch",
views: {
'testView': {
template: '<div><span>{{params}} , I load after the promise</span></div>',
controller: "mainSearch",
}
},
resolve: {
entityParams: ['$stateParams', 'mainSearch', function ($stateParams) { console.log("I load before the view as i contain a promise")
return $stateParams
}]
}
})
// in mainSearch.js
state.go("mainSearch", {
params: httpfactory.getResult('GET', param)
})
// in http-factory module
var app = angular.module("http-factory", []);
app.factory('httpfactory', ['$http', function ($http) {
$scope.getResult = function (callType, param) {
switch (callType) {
case 'POST':
$http.post('/abcurl', 'requestBody', {
withCredentials: true,
headers: {
"abc": "abc"
}
})
break;
case 'GET':
return $http.get('/gttportal/api/search', {
params: param,
withCredentials: true
})
}
break;
}
}]);
this is how i have my app.js and module congifured
app = angular.module('myapp', ['http-factory','mainsearch']
app.config(function ($stateProvider, $urlRouterProvider, httpfactory) {...
this is how i have my mainsearch module and function configured:
.module('mainsearch', ['http-factory'])
function ($rootScope, $scope, $http, $state, $stateParams, httpfactory)
I have an angular app that needs to do a quick http request to get some config information before the rest of the application is initiated, at least before the controllers. Looked into using $UrlRouterProvider, but I did not figure out how to make the app wait for the http be done.
What I need to be finished:
$http({method: 'GET', url: '/config'}).then(function(res) {
configProvider.setConfig(res.data.config);
}
You can create a separate js file where you can make http request and then initialize/bootstrap your app via js code instead of ng-app in html code.
Refer the below code:
(function() {
var application, bootstrapApplication, fetchData;
application = angular.module('app');
fetchData = function() {
var $http, initInjector;
initInjector = angular.injector(['ng']);
$http = initInjector.get('$http');
$http.get('<url>');
};
bootstrapApplication = function() {
angular.element(document).ready(function() {
angular.bootstrap(document, ['app']);
});
};
fetchData().then(bootstrapApplication);
})();
I hope it helps.
Resolve must be declared on state, not on the view
change
.state('app', {
abstract: true,
url:'/',
views: {
"content": {
templateUrl: "myurl.html"
},
resolve {
myVar: ['$http', 'myService', function($http, myService) {
return $http({method: 'GET', url:'url'})
.then(function(res) { //do stuff })
to
.state('app', {
abstract: true,
url:'/',
views: {
"content": {
templateUrl: "myurl.html"
}
},
resolve {
myVar: ['$http', 'myService', function($http, myService) {
return $http({method: 'GET', url:'url'})
.then(function(res) { //do stuff })...
I basically need to call a server that's will return me a JSON structure before load the controller.
I was using many methods to archive that, but it's not working. It's don't show me any error and the page got blank. Any clue about what's going on ?
This is my controller..
angular
.module('app',[
'ngAnimate',
'ui.router',
'ui.bootstrap',
'ngCookies'
])
.run(function($rootScope) {
$rootScope.backendServer = "http://localhost:5000/";
})
.config(['$urlRouterProvider','$stateProvider', function($urlRouterProvider,$stateProvider) {
$stateProvider
.state('cms',{
url: '/my',
templateUrl: './app/templates/my.html',
controller : 'my',
resolve: {
dbState: function ($q) {
var defer = $q.defer();
Database.check().then(function (s) {
defer.resolve(s);
});
return defer.promise;
}
}
})
}])
.controller(function ($scope){
})
...and this is my service:
angular
.module('app')
.factory('Database',['$http', '$rootScope','$q', function($http, $rootScope, $q) {
return {
check: function () {
var call = $rootScope.backendServer + 'cms/database/check';
return $http.get(call);
}
}
}]);
don't create a defer object when you already returning a promise. so remove the defer and just return the factory function
also, inject the Database service to resolve
resolve: {
dbState: function(Database) {
return Database.check()
}
}
In the controller catch it like this
.controller("ctrl", function($scope, dbState) {
console.log(dbState.data)
})
Demo
First, thanks for your help in advance. I'm a noob to angular though I did search quite a bit trying to resolve this issue. I'm guessing I missed something obvious. I'm using ui-router and using the resolve property to call a resource and can't get it for the life of me to pass the params to the web service.
First, my routes and states:
(function () {
"use strict";
var app = angular.module("MyModule",
["ui.router",
"ngResource",
"common.services"]);
app.config(["$stateProvider", '$urlRouterProvider',
function ($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise("/");
$stateProvider.state("home", {
url: "/",
templateUrl: "welcomeView.html"
})
$stateProvider.state("vehicleList", {
url: "/vehicles",
templateUrl: "App/Vehicles/vehicleListView.html",
controller: "VehicleListController as vm"
})
$stateProvider.state("vehicleEdit", {
url: "/vehicles/edit/:vin",
templateUrl: "App/Vehicles/vehicleEditView.html",
controller: "VehicleEditController as vm",
resolve: {
vehicleResource: "vehicleResource",
vehicle: function (vehicleResource, $stateParams) {
var vehicleVIN = $stateParams.vin;
return vehicleResource.get(
{ vin: $stateParams.vin }).$promise;
}
}
})
$stateProvider.state("vehicleDetails", {
url: "/vehicles/:vin",
templateUrl: "App/Vehicles/vehicleDetailsView.html",
controller: "VehicleDetailsController as vm",
resolve: {
vehicleResource: "vehicleResource",
vehicle: function (vehicleResource, $stateParams) {
var vehicleVIN = $stateParams.vin;
return vehicleResource.get(
{ vin: 'T123432342' }).$promise;
}
}
})
}
]);
}());
Note that you see a couple of varieties of passing the vin is as I've tried numerous ways with passing in the variable vehicleVIN, a string, etc. The vehicleVIN variable does assign properly there so injecting $stateParams or passing the vin to it doesn't seem to be the problem.
Here is the resource:
(function () {
"use strict";
angular
.module("common.services")
.factory("vehicleResource",
["$resource",
"appSettings",
vehicleResource]);
function vehicleResource($resource, appSettings) {
return $resource(appSettings.serverPath + "/api/Vehicle/:vin", { vin: '#vin' },
{
'update': { method: 'PUT' },
'details': { method: 'GET' },
'query': { method: 'GET', isArray = true }
});
}
}());
Here is common.services:
(function () {
"use strict";
angular
.module("common.services", ["ngResource"])
.constant("appSettings",
{
serverPath: "http://localhost:8098"
});
}());
And here is the service end of it (Asp.Net WebAPI):
// GET api/Vehicle
[EnableQuery(AllowedQueryOptions = AllowedQueryOptions.All, AllowedOrderByProperties = "Name")]
[ResponseType(typeof(IQueryable<IEnumerable<IVehicle>>))]
public IHttpActionResult Get()
{
return ListOfVehicles...blah..blah
}
// GET api/Vehicle/5
[ResponseType(typeof(IQueryable<IVehicle>))]
public IHttpActionResult Get(string vin)
{
return SingleVehicle...blah...blah
}
Every time I execute it, the breakpoint hits Get (without the vin parameter) and when I run fiddler, it looks like it's sending an empty body.
Any ideas on what is going on? Much appreciated!
i am new to angular and facing this exception when trying to retrieve a list of blog-posts from rails backend.
can anyone help me please, i am unable to find the exact solution of this problem.
Error: [$injector:unpr] Unknown provider: PostProvider <- Post
http://errors.angularjs.org/1.2.22/$injector/unpr?p0=PostProvider%20%3C-%20Post
var myApp = angular.module('Emangu', ['ngRoute', 'ngResource']);
//Routes
myApp.config([
'$routeProvider', '$locationProvider', function ($routeProvider, $locationProvider) {
$routeProvider.when('/blog', {
templateUrl: '/templates/posts/index.html',
controller: 'PostListCtr'
});
}
]);
//Controllers
myApp.controller("PostListCtr", ['$scope', '$http', '$resource', 'Posts', 'Post', '$location', function ($scope, $http, $resource, Posts, Post, $location) {
alert("hello");
$scope.posts = Posts.query();
$scope.deletePost = function (Post) {
if (confirm("Are you sure you want to delete this Post?")) {
Post.delete({ id: Post }, function () {
$scope.posts = Posts.list();
$location.path('/');
});
}
};
}]);
//resources
myApp.factory('Posts', ['$resource', function ($resource) {
return $resource('/posts.json', {}, {
query: { method: 'GET', isArray: true },
create: { method: 'POST' }
})
}]);
Add Post factory (service) or remove it from PostListCtr dependencies