Angular factory $resource: 404 Not Found - angularjs

I'm new to Angular and I've been working on an Airline SPA which reads sample data from json file. The app works fine when running on nodejs (localhost:3000/airports), however it shows this error when I check it out on github: GET https://nlmazhari.github.io/airports 404 Not Found
this is my app.js:
angular.module('airline', ['airlineServices'])
.config(airlineRouter);
function airlineRouter ($routeProvider) {
$routeProvider
.when('/', {templateUrl: 'partials/destinations.html',
controller: 'DestinationsCtrl'})
.when('/airports/:airportCode', {
templateUrl: 'partials/airport.html',
controller: 'AirportCtrl'
})
.when('/flights', {
templateUrl: 'partials/flights.html',
controller: 'FlightsCtrl'})
.when('/reservations', {
templateUrl: 'partials/reservations.html',
controller: 'ReservationsCtrl'});
}
these are my controllers:
function AirportCtrl ($scope, $routeParams, Airport) {
$scope.currentAirport = Airport.get({
airportCode: $routeParams.airportCode
});
}
function DestinationsCtrl ($scope, Airport) {
$scope.setActive('destinations');
$scope.sidebarURL = 'partials/airport.html';
$scope.currentAirport = null;
$scope.setAirport = function (code) {
$scope.currentAirport = Airport.get({airportCode: code});
};
$scope.airports = Airport.query();
}
and this is my services.js:
angular.module('airlineServices', ['ngResource'])
.factory('Airport', function ($resource) {
return $resource('/airports/:airportCode');
})
.factory('Flights', function ($resource) {
return $resource('/flights');
})
.factory('Reservations', function ($resource) {
return $resource('/reservations');
});
can anybody guide me? why am I getting this error?

Related

Angular Routing and Binding data from controller

I have my angular routing like th below code
var app = angular.module('mainApp', ['ngRoute']);
app.config(function ($routeProvider) {
$routeProvider.when('/', {
templateUrl: '/DeclarationForms/V1/EmployeeProfile.html',
controller: 'empController'
}).when('/DeclarationAndIndemnityBond.html', {
templateUrl: '/DeclarationForms/V1/DeclarationAndIndemnityBond.html',
controller: 'declarationController'
}).otherwise({
redirectTo: "/"
});
app.controller('empController', function ($scope, $http) {
var resultPromise = $http.get("../ViewForms/GetData/", { params: { ProcName: "SP_EmployeeProfile_GetList" } });
resultPromise.success(function (data) {
console.log(data);
$scope.employeeProfile = data;
});
});
});
The empController calls my controller action with a parameter as per the code
$http.get("../ViewForms/GetData/", { params: { ProcName: "SP_EmployeeProfile_GetList" } });
The controller's action code is as follows
[HttpGet]
[AllowAnonymous]
public ActionResult GetData(string ProcName)
{
if(Session["UserJDRECID"]==null || Session["UserJDRECID"].ToString()=="0")
{
return RedirectToAction("Login", "User_Login");
}
else
{
var UsrJDID = Convert.ToInt32(Session["UserJDRECID"]);
DataSet dt = Helper.PopulateData(ProcName, UsrJDID);
string JSONString = string.Empty;
JSONString = JsonConvert.SerializeObject(dt);
return Json(JSONString, JsonRequestBehavior.AllowGet);
}
}
The form get loaded properly as per the code
templateUrl: '/DeclarationForms/V1/EmployeeProfile.html',
but it don't call my action GetData from where I suppose to bind the EmployeeProfile.html
If I change my angular controller like below code this still don't work
app.controller('empController', function ($scope)
{
console.log("hi"); alert();
});
My console gives below error
Error: error:areq
Bad Argument
Please help me I stuck here.
Thanks in advance.
You can't use "../" inside your $http.get.
I don`t know how your project is setup, but you can try:
$http.get("/ViewForms/GetData/", { params: { ProcName: "SP_EmployeeProfile_GetList" } });
In that case the ViewForms is the name of your controller and it needs to be in the root or pass the complete url. Make sure you are passing all the folders then Controller then your action.
Example: http://www.dotnetcurry.com/angularjs/1202/angular-http-service-aspnet-mvc
I change my code as follows and this worked for me.
var app = angular.module('mainApp', ['ngRoute']);
app.config(function ($routeProvider) {
$routeProvider.
when('/', {
templateUrl: '/DeclarationForms/V1/EmployeeProfile.html',
controller: 'empController'
})
otherwise({
redirectTo: "/"
});
});
app.controller('empController', ['$scope', '$http', EmployeeProfile]);
function EmployeeProfile($scope, $http) {
$http.get("../ViewForms/GetData", { params: { ProcName: "SP_EmployeeProfile_GetList" } })//Done
.then(function (response) {
var mydata = $.parseJSON((response.data));
$scope.employeeProfile = $.parseJSON(mydata);
});
}

UI Resolve is not injecting into controller (data is undefined)

I've looked at similar questions but I can't seem to understand what I am missing. Basically, I have a service that gets data from the server, and I am trying to get that data into a controller through UI-Router's resolve property. However, after following numerous tutorials and documentations, I can't get the controller to find the data, so to speak. Everything comes up as undefined. I am hoping someone can help me understand what is happening. My code is below.
services.js
myServices.factory('SoundCloudService', ['$http', '$log', '$sce', function($http, $log, $sce) {
function getPlayerHtml() {
return $http.get('/get-site-data').then(function(oEmbed) {
return $sce.trustAsHtml(oEmbed.data.player);
});
};
function getSiteAbout() {
return $http.get('/get-site-data').then(function(oEmbed) {
return $sce.trustAsHtml(oEmbed.data.about);
});
}
function getAllTracks() {
return $http.get('/get-all-tracks').then(function(tracks) {
return JSON.parse(tracks.data);
});
};
function getAllPlaylists() {
return $http.get('/get-playlists').then(function(playlists) {
return JSON.parse(playlists.data);
})
};
function getPlaylist(pid) {
return $http.post('/get-playlist', pid, $http.defaults.headers.post).then(function(playlist) {
return playlist.data;
});
};
function getXMostTrendingFrom(x, playlist) {
var i, trending = [];
playlist.sort(function(a, b) { return b.playback_count - a.playback_count} );
for(i=0;i<x;i++) {
trending.push(all_tracks[i]);
}
return trending;
};
return {
getAllTracks: getAllTracks,
getAllPlaylists: getAllPlaylists,
getPlayerHtml: getPlayerHtml,
getSiteAbout: getSiteAbout,
getXMostTrendingFrom: getXMostTrendingFrom,
getPlaylist: getPlaylist,
};
}]);
app.js
myApp.config(['$stateProvider', '$urlRouterProvider', 'ngMetaProvider',
function($stateProvider, $urlRouterProvider, ngMetaProvider) {
$urlRouterProvider.otherwise('/');
$stateProvider
.state('main', {
url: '',
template: '<ui-view/>',
abstract:true,
controller: 'MainController',
resolve: {
player: function(SoundCloudService) { return SoundCloudService.getPlayerHtml(); },
about: function(SoundCloudService) { return SoundCloudService.getSiteAbout(); },
}
})
.state('main.home', {
url: '/',
templateUrl: '../static/partials/home.html',
controller: 'IndexController',
})
.state('main.team', {
url: '/team',
templateUrl: '../static/partials/team.html',
controller: 'TeamController',
})
.state('main.contact', {
url: '/contact',
templateUrl: '../static/partials/contact.html',
controller: 'ContactController',
})
.state('main.resources', {
url: '/resources',
templateUrl: '../static/partials/resources.html',
controller: 'ResourcesController',
})
.state('main.listen-to', {
url: '/listen-to',
templateUrl: '../static/partials/listen-to.html',
controller: 'ListenController',
})
.state('main.listen-to.season', {
url: '/listen-to/:season',
templateUrl: '../static/partials/listen-to.season.html',
controller: 'ListenController',
})
.state('main.listen-to.season.episode', {
url: '/listen-to/:season/:episode',
templateUrl: '../static/partials/listen-to.season.episode.html',
controller: 'ListenController',
})
.state('main.read', {
url: '/read',
templateUrl: '../static/partials/read.html',
controller: 'ReadController',
})
.state('main.read.post', {
url: '/read/:post',
templateUrl: '../static/partials/read.post.html',
controller: 'ReadController',
})
}
]);
controller.js
myControllers.controller('MainController', ['$scope', '$log', 'PageTitleService',
function($scope, $log, PageTitleService, player) {
$log.log(player); /* This is always undefined */
}
]);
[UPDATE]
As pointed out by Hadi in the answer below, I placed player in the array, and the controller now looks like this:
skodenControllers.controller('MainController', ['$scope', '$log', '$sce', 'PageTitleService', 'player',
function($scope, $log, $sce, PageTitleService, player) {
$log.log(player);
}
]);
The console DOES show the data, but only after an error as such:
Error: [$injector:unpr]
http://errors.angularjs.org/1.3.2/$injector/unpr?p0=playerProvider%20%3C-%20player
at angular.js:38
at angular.js:3930
at Object.d [as get] (angular.js:4077)
at angular.js:3935
at d (angular.js:4077)
at Object.e [as invoke] (angular.js:4109)
at F.instance (angular.js:8356)
at angular.js:7608
at r (angular.js:347)
at I (angular.js:7607)
Hopefully someone can lead me in the right direction.
You forgot pass player into array. change to this
myControllers.controller('MainController', ['$scope', '$log',
'PageTitleService','player',
function($scope, $log, PageTitleService, player) {
$log.log(player); /* This is always undefined */
}
]);
As myServices and myControllers are both modules, ensure you add them as dependencies of myApp module.
// init myApp module
angular.module('myApp', ['myServices', 'myControllers']);
Edit
Some leads :
According to the documentation, when using ui-router nested views, child views (state name = main.xxx) must declare the parent state, so you must add parent: "main" or child views won't inherit resolved properties of main state controller
As siteDate is loaded asynchronously in SoundCloudService (services.js:23), you cannot be sure it will be available in your controllers which are loaded at the same time.
Instead, add a getSiteDate() method to SoundCloudService which returns a promise. siteData is then cached and immediately return by the promise.
For example :
/**
* #name getSiteData
* #description Scrap site data
* #returns {promise} a promise
*/
function getSiteData() {
var deferred = $q.defer();
if(siteData) {
deferred.resolve(siteData);
}
else {
$http.get('/get-site-data').then(function(response) {
siteData = response.data;
deferred.resolve(siteData);
}, function(err) {
deferred.reject(err.message);
});
}
return deferred.promise;
}
Why trying to map SoundCloudService to siteData ? You should simply inject SoundCloudService in controllers that use it :
For example :
skodenControllers.controller('MainController', ['$scope', '$log', '$sce', 'PageTitleService', 'SoundCloudService',
function($scope, $log, $sce, PageTitleService, SoundCloudService) {
// Note: getSiteData() could use a cache inside the service
SoundCloudService.getSiteData().then(function(siteData) {
...
});
}

AngularJS: Error on Factory and routeProvider

In "routeProvider" I have the "objectStats" on resolve, but my controller does not seem to understand it. (I found several problems like on stackoverflow, but no solution solved my error)
My code:
var app = angular.module('AppLearning', ['ngRoute','easypiechart']);
app.config(['$routeProvider',function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'index.html',
controller: 'AppCtrl',
resolve: {
objectStats: function(statsFactory) {
return statsFactory.getStatsFollow();
}
}
}).
otherwise({
redirectTo: '/home'
});
}]);
app.controller('AppCtrl', ['$scope', '$http', 'objectStats', function ($scope, $http, objectStats) {
$scope.statsUnfollow = objectStats.data;
$scope.percent = 65;
$scope.pieOptions = {
animate:{
duration:2000,
enabled:true
},
trackColor: '#e5e5e5',
barColor: '#3da0ea',
scaleColor:false,
lineWidth:5,
lineCap:'square'
};
}]);
app.factory('statsFactory', ['$http', function($http) {
return {
//Code edited to create a function as when you require service it returns object
//by default so you can't return function directly. That's what understand...
getStatsFollow: function (type) {
var q = $q.defer();
$http.get('/api/stats/follow').success(function (data) {
q.resolve(function() {
var settings = jQuery.parseJSON(data);
return settings[type];
});
});
return q.promise;
}
}
}]);
Error: [$injector:unpr] Unknown provider: objectStatsProvider <- objectStats
http://errors.angularjs.org/1.2.9/$injector/unpr?p0=objectStatsProvider%20%3C-%20objectStats
minErr/<#https://ajax.googleapis.com/ajax/libs/angularjs/1.2.9/angular.js:78:12
createInjector/providerCache.$injector<#https://ajax.googleapis.com/ajax/libs/angularjs/1.2.9/angular.js:3546:19
getService#https://ajax.googleapis.com/ajax/libs/angularjs/1.2.9/angular.js:3673:39
createInjector/instanceCache.$injector<#https://ajax.googleapis.com/ajax/libs/angularjs/1.2.9/angular.js:3551:28
getService#https://ajax.googleapis.com/ajax/libs/angularjs/1.2.9/angular.js:3673:39
invoke#https://ajax.googleapis.com/ajax/libs/angularjs/1.2.9/angular.js:3700:1
instantiate#https://ajax.googleapis.com/ajax/libs/angularjs/1.2.9/angular.js:3721:23
$ControllerProvider/this.$gethttps://ajax.googleapis.com/ajax/libs/angularjs/1.2.9/angular.js:6772:18
nodeLinkFn/<#https://ajax.googleapis.com/ajax/libs/angularjs/1.2.9/angular.js:6185:34
forEach#https://ajax.googleapis.com/ajax/libs/angularjs/1.2.9/angular.js:310:11
nodeLinkFn#https://ajax.googleapis.com/ajax/libs/angularjs/1.2.9/angular.js:6172:11
compositeLinkFn#https://ajax.googleapis.com/ajax/libs/angularjs/1.2.9/angular.js:5636:15
compositeLinkFn#https://ajax.googleapis.com/ajax/libs/angularjs/1.2.9/angular.js:5639:13
compositeLinkFn#https://ajax.googleapis.com/ajax/libs/angularjs/1.2.9/angular.js:5639:13
publicLinkFn#https://ajax.googleapis.com/ajax/libs/angularjs/1.2.9/angular.js:5541:30
bootstrap/doBootstrap/https://ajax.googleapis.com/ajax/libs/angularjs/1.2.9/angular.js:1304:11
$RootScopeProvider/this.$gethttps://ajax.googleapis.com/ajax/libs/angularjs/1.2.9/angular.js:11955:16
$RootScopeProvider/this.$gethttps://ajax.googleapis.com/ajax/libs/angularjs/1.2.9/angular.js:12055:18
bootstrap/doBootstrap/<#https://ajax.googleapis.com/ajax/libs/angularjs/1.2.9/angular.js:1302:9
invoke#https://ajax.googleapis.com/ajax/libs/angularjs/1.2.9/angular.js:3710:14
bootstrap/doBootstrap#https://ajax.googleapis.com/ajax/libs/angularjs/1.2.9/angular.js:1300:1
bootstrap#https://ajax.googleapis.com/ajax/libs/angularjs/1.2.9/angular.js:1314:1
angularInit#https://ajax.googleapis.com/ajax/libs/angularjs/1.2.9/angular.js:1263:5
#https://ajax.googleapis.com/ajax/libs/angularjs/1.2.9/angular.js:20555:5
b.Callbacks/c#https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js:3:7852
b.Callbacks/p.fireWith#https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js:3:8658
.ready#https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js:3:3264
H#https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js:3:693

AngularJS UI router: Block view

Right now i am making an AngularJS+UI router install application. But i have a problem, the problem is, that i want to disable access to the views, associated with the install application. I want to do it in resolve in the state config.
But the problem is i need to get the data from a RESTful API, whether the application is installed or not. I tried making the function, but it loaded the state before the $http.get request was finished.
Here was my code for the resolve function:
(function() {
var app = angular.module('states', []);
app.run(['$rootScope', '$http', function($rootScope, $http) {
$rootScope.$on('$stateChangeStart', function() {
$http.get('/api/v1/getSetupStatus').success(function(res) {
$rootScope.setupdb = res.db_setup;
$rootScope.setupuser = res.user_setup;
});
});
}]);
app.config(['$stateProvider', '$urlRouterProvider', function($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise("/404");
$stateProvider.state('db-install', {
url: "/install/db",
templateUrl: 'admin/js/partials/db-install.html',
controller: 'DBController',
resolve: {
data: function($q, $state, $timeout, $rootScope) {
var setupStatus = $rootScope.setupdb;
var deferred = $q.defer();
$timeout(function() {
if (setupStatus === true) {
$state.go('setup-done');
deferred.reject();
} else {
deferred.resolve();
}
});
return deferred.promise;
}
}
})
.state('user-registration', {
url: "/install/user-registration",
templateUrl: "admin/js/partials/user-registration.html",
controller: "RegisterController"
})
.state('setup-done', {
url: "/install/setup-done",
templateUrl: "admin/js/partials/setup-done.html"
})
.state('404', {
url: "/404",
templateUrl: "admin/js/partials/404.html"
});
}]);
})();
EDIT:
Here is what my ajax call returns:
Try this way:
$stateProvider.state('db-install', {
url: "/install/db",
templateUrl: 'admin/js/partials/db-install.html',
controller: 'DBController',
resolve: {
setupStatus: function($q, $state, $http) {
return $http.get('/api/v1/getSetupStatus').then(function(res) {
if (res.db_setup === true) {
$state.go('setup-done');
return $q.reject();
}
return res;
});
}
}
})
Then inject setupStatus in controller:
.state('setup-done', {
url: "/install/setup-done",
templateUrl: "admin/js/partials/setup-done.html",
controller: ['$scope', 'setupStatus', function ($scope, setupStatus) {
$scope.setupdb = setupStatus.db_setup;
$scope.setupuser = setupStatus.user_setup;
}]
})

Angularjs - Restangular call inside factory/service

I am using factory as follows:
var appModule = angular.module('appModule', ['ngRoute','restangular']);
appModule
.config(['$routeProvider', function($routeProvider) {
$routeProvider
.when('/home', {
templateUrl: 'home.html',
controller: 'ngHomeControl'
})
.when('/contacts', {
templateUrl: 'contacts.html',
controller: 'ngContactControl'
});
}]);
appModule
.factory('testFactory', function testFactory(Restangular) {
return {
getFriendList: function() {
return Restangular
.all('api/users/getfriendsinvitations/')
.getList()
.then(function(response) {
//
});
}
}
});
appModule
.controller('ngHomeControl', function($scope, testFactory) {
$scope.homeFriends = testFactory.getFriendList();
});
appModule
.controller('ngContactControl', function($scope, testFactory) {
$scope.contactFriends = testFactory.getFriendList();
});
Here I can't get the value for $scope.homeFriends & $scope.contactFriends from the Restangular call. Can anyone suggest to me how to get values from Restangular call using factory/service?
Finally I found:
appModule
.factory('testFactory', ['Restangular', function(Restangular) {
return {
getFriendList: Restangular
.all('api/users/getfriendsinvitations/')
.getList();
}
}]);
testFactory.getFriendList.then(function(homeFriends) {
$scope.homeFriends = homeFriends;
}

Resources