Error: [$injector:modulerr] Failed to instantiate module ngFoursquare due to - angularjs

I'm not too much angularjs information . I want to make the ionic foursquare integration . But do not resolve the error.
Uncaught Error: [$injector:modulerr] Failed to instantiate module starter due to:
Error:
[$injector:modulerr] Failed to instantiate module ngFoursquare due to:
Error: [$injector:nomod] Module 'ngFoursquare' is not available!
You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.
app.js
angular.module('starter', ['ionic', 'starter.controllers' ,'ngFoursquare'])
.constant('CLIENT_ID', 'X4ITCR1UHKU2EKFVIBEZRRYX52W2I2I3I3ZN5K0A2M3YDIKS')
.run(function($ionicPlatform) {
$ionicPlatform.ready(function() {
if (cordova.platformId === 'ios' && window.cordova && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
cordova.plugins.Keyboard.disableScroll(true);
}
if (window.StatusBar) {
StatusBar.styleDefault();
}
});
})
.config(function ($stateProvider, $urlRouterProvider, FoursquareProvider) {
$stateProvider
.state('app', {
url: '/app',
abstract: true,
templateUrl: 'templates/menu.html',
controller: 'AppCtrl'
})
.state('app.login', {
url: '/login',
views: {
'menuContent': {
templateUrl: 'templates/login.html',
controller: 'LoginCtrl'
}
}
})
//$urlRouterProvider.otherwise('/app/playlists');
$urlRouterProvider.otherwise({
resolve : {
token: function ($location) {
var match = $location.path().match(/access_token=(.*)/)
if(match){
FoursquareProvider.token = match[1]
}
}
}
,templateUrl: 'templates/login.html'
,controller:'LoginCtrl'
})
});
controllers.js
angular.module('starter.controllers', [])
.controller('AppCtrl', function($scope, $ionicModal, $timeout) {
$scope.loginData = {};
$ionicModal.fromTemplateUrl('templates/login.html', {
scope: $scope
}).then(function(modal) {
$scope.modal = modal;
});
$scope.closeLogin = function() {
$scope.modal.hide();
};
$scope.login = function() {
$scope.modal.show();
};
$scope.doLogin = function() {
console.log('Doing login', $scope.loginData);
$timeout(function() {
$scope.closeLogin();
}, 1000);
};
})
.controller('LoginCtrl', function($scope,Foursquare, $log, CLIENT_ID, $location) {
var match = $location.path().match(/access_token=(.*)/)
$scope.userId = 'self'
$scope.client_id = CLIENT_ID
$scope.redirect_uri = encodeURIComponent(location.origin+location.pathname)
$scope.access_token = match && match[1] || ''
$scope.clear = function () {
$scope.userId=null
$scope.venueId=null
$scope.ll=null
$scope.checkinId=null
}
$scope.getUser = function (userId) {
$scope.data = Foursquare.Users.get({
userId: userId
},function (data) {
$scope.user = data.response.user
})
}
$scope.getUserLists = function (userId) {
$scope.data = Foursquare.Users.lists({
userId: userId
})
}
$scope.searchVenues = function (ll) {
$scope.data = Foursquare.Venues.search({ll:ll})
}
$scope.getVenue = function (venueId) {
$scope.data = Foursquare.Venues.get({
venueId:venueId
})
}
$scope.addCheckin = function (venueId,broadcast) {
$scope.data = Foursquare.Checkins.add({
venueId:venueId,
broadcast:broadcast
})
}
$scope.getCheckin = function (checkinId) {
$scope.data = Foursquare.Checkins.get({
checkinId:checkinId
})
}
$scope.search = function () {
navigator.geolocation.getCurrentPosition(function (pos) {
$scope.$apply(function () {
$scope.pos = pos
$scope.data = Foursquare.search(pos)
})
})
}
$scope.getList = function (listId) {
$scope.data = Foursquare.Lists.get({
listId:listId
})
}
$scope.addList = function (name) {
$scope.data = Foursquare.Lists.add({
name:name
})
}
})
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
<title></title>
<link href="lib/ionic/css/ionic.css" rel="stylesheet">
<link href="css/style.css" rel="stylesheet">
<!-- IF using Sass (run gulp sass first), then uncomment below and remove the CSS includes above
<link href="css/ionic.app.css" rel="stylesheet">
-->
<script src="js/platformOverrides.js"></script>
<!-- ionic/angularjs js -->
<script src="lib/ionic/js/ionic.bundle.js"></script>
<!-- cordova script (this will be a 404 during development) -->
<script src="cordova.js"></script>
<!-- your app's js -->
<script src="js/foursquare.js"></script>
<script src="js/app.js"></script>
<script src="js/controllers.js"></script>
</head>
<body ng-app="starter">
<ion-nav-view></ion-nav-view>
</body>
</html>
foursquare.js
angular.module('ngFoursquare',["ngResource"])
.constant('BASE_API_URL','https://api.foursquare.com/v2')
.constant('encodeParam',function (data) {
return data && Object.keys(data).map(function (k) {
return encodeURI(k)+'='+encodeURI(data[k])
}).join('&')
})
.config(function ($provide,$resourceProvider,$httpProvider) {
var $hp = angular.copy($httpProvider)
,$rp = angular.copy($resourceProvider)
i = 0
$provide.decorator('$cacheFactory',function ($delegate) {
return function (cacheId,options) {
if(cacheId=='$http'){
cacheId+=''+i++
}
$delegate(cacheId,options)
}
})
delete $hp.defaults.headers.common["X-Requested-With"]
$provide.provider('$customHttp',$hp)
$rp.$get[0]="$customHttp"
$provide.provider('$customResource',$rp)
})
.provider('Foursquare',function (encodeParam) {
var FoursquareProvider = {
'$get': function ($customResource,$q,BASE_API_URL) {
var $resource=$customResource
,params = {
oauth_token: FoursquareProvider.token || ''
,v: '20130425'
}
,Foursquare = {
token: function (token) {
FoursquareProvider.token = token
}
,Users: $resource(BASE_API_URL+'/users/:userId/:action',
{},{
lists:{
method:'GET',
params: angular.extend({action:'lists'},params)
},
get:{
method:'GET',
params: params
}
})
,Venues : $resource(BASE_API_URL+'/venues/:venueId/:action',
{},{
search: {
method: 'GET'
,params: angular.extend({action:'search'},params)
},
get: {
method: 'GET',
params: params
}
})
,Checkins: $resource(BASE_API_URL+'/checkins/:checkinId/:action',
{},{
add: {
method: 'POST',
params: angular.extend({action:'add'},params),
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
transformRequest: encodeParam
},
get: {
method: 'GET',
params: params
}
})
,Lists: $resource(BASE_API_URL+'/lists/:listId/:aspect/:action',
{},{
get: {
method:'GET',
params: params
},
add: {
method: 'POST',
params: angular.extend({action:'add'}, params),
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
transformRequest: encodeParam
}
})
,search:function (position) {
return $q.when(position).then(function (pos) {
var c = pos.coords,
ll = "" + c.latitude + "," + c.longitude
return ll
})
.then(function (ll) {
var deferred = $q.defer()
Foursquare.Venues.search({
ll:ll
},deferred.resolve,deferred.reject)
return deferred.promise
})
}
}
return Foursquare
}
}
return FoursquareProvider
})

I think you have not included angular-resource.js in your index.html.
You need to include it first.Then after your ngFoursquare module is created
and then it is available for injection in other module.

Related

Angular injector error with Filestack

I am attempting to integrate Filestack into an existing app. I think I am having issues with how those modules are configured, but can't get the ordering correct. I receive this error:
angular.js:38Uncaught Error: [$injector:modulerr] http://errors.angularjs.org/1.5.6/$injector/modulerr?p0=myApp&p1=TypeError%…ogleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.5.6%2Fangular.min.js%3A20%3A156)
Here is the routing file:
(function () {
var app = angular.module('myApp', ['ngRoute', 'angular-filepicker']);
// ROUTING
app.config(['$routeProvider', function($routeProvider, filepickerProvider){
$routeProvider
.when('/home', {
templateUrl: "views/home.html",
controller: "HomeController"
})
.when('/shopping-list/:id', {
templateUrl: "views/shopping-list.html",
controller: 'ShoppingListController'
})
.when('/add-list', {
templateUrl: "views/add-list.html",
controller: 'AddListController'
})
.otherwise({
redirectTo: '/home'
});
filepickerProvider.setKey('XXXXXXX');
}]);
Here is the index.html:
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<!-- CDN SCRIPTS -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/randomcolor/0.4.4/randomColor.min.js"></script>
<!-- Font Awesome -->
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-T8Gy5hrqNKT+hzMclPo118YTQO6cYprQmhrYwIiQ/3axmI1hQomh7Ud2hPOy8SP1" crossorigin="anonymous">
<!-- Bootstrap -->
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Tara's Custom CSS -->
<link rel="stylesheet" type="text/css" href="css/style.css">
<!-- Imported Google Fonts -->
<link href="https://fonts.googleapis.com/css?family=Rubik" rel="stylesheet">
<title>Shopping List</title>
</head>
<body>
<div ng-include="'partials/header.html'"></div>
<main ng-view></main>
<!--ANGULAR SCRIPTS-->
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular-route.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.0/angular-animate.min.js"></script>
<script src="/bower_components/filepicker-js/filepicker.js"></script>
<script src="/bower_components/angular-filepicker/dist/angular_filepicker.js"></script>
<script type="text/javascript" src="//api.filestackapi.com/filestack.js"></script>
<script type="text/javascript" src="js/index.js"></script>
<script type="text/javascript" src="js/controllers/controller-header.js"></script>
<script type="text/javascript" src="js/controllers/controller-home.js"></script>
<script type="text/javascript" src="js/controllers/controller-add-list.js"></script>
<script type="text/javascript" src="js/controllers/controller-shopping-list.js"></script>
</body>
</html>
And the controller that is using Filestack:
(function () {
'use strict';
var app = angular.module('myApp');
app.controller('ShoppingListController', ['$scope', '$http', '$routeParams', 'API_BASE', '$location', function($scope, $http, filepickerService, $routeParams, API_BASE, $location){
// GET SPECIFIC LIST
$scope.list = [];
var id = $routeParams.id;
$http({
method: 'GET',
url: API_BASE + 'shopping-lists/' + id
}).then(function successCallback(response) {
$scope.list = response.data[0];
}, function errorCallback(response) {
console.log('it did not work');
console.log(response.statusText);
});
// REMOVE LIST
$scope.removeList = function(){
var id = $scope.list.id;
console.log(id);
$http.delete(API_BASE + 'shopping-lists/' + id)
.success(function (data, status, headers, config) {
console.log('you deleted :' + $scope.list);
})
.error(function (data, status, header, config) {
});
$location.path('/home');
};
// RANDOM ID
function makeid()
{
var text = "";
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for( var i=0; i < 20; i++ ){
text += possible.charAt(Math.floor(Math.random() * possible.length));
}
text += Date.now();
return text;
}
// ADD ITEM
$scope.addItem = function(){
var created = new Date();
var newID = makeid();
if($scope.list.hasOwnProperty('items') === false){
$scope.list.items = [];
}
$scope.list.items.push({
name : $scope.newItem.name,
priority : $scope.newItem.priority,
note: $scope.newItem.note,
picture: $scope.newItem.picture,
isChecked: false,
listId: $scope.list.id,
created: created,
id: newID
});
// console.log($scope.list.items);
$http.put(API_BASE + 'shopping-lists/', $scope.list)
.success(function (data, status, headers, config) {
})
.error(function (data, status, header, config) {
});
// Reset input fields after submit
$scope.newItem = {
name: "",
priority: "",
note: ""
};
};
// ADD ITEM IMAGE
$scope.upload = function(){
filepickerService.pick(
{
mimetype: 'image/*',
language: 'en',
services: ['COMPUTER','DROPBOX','GOOGLE_DRIVE','IMAGE_SEARCH', 'FACEBOOK', 'INSTAGRAM'],
openTo: 'IMAGE_SEARCH'
},
function(Blob){
console.log(JSON.stringify(Blob));
$scope.newItem.picture = Blob;
$scope.$apply();
});
};
// REMOVE ITEM
$scope.removeItem = function(item){
var removedItem = $scope.list.items.indexOf(item);
$scope.list.items.splice(removedItem, 1);
$http.put(API_BASE + 'shopping-lists', $scope.list)
.success(function (data, status, headers, config) {
})
.error(function (data, status, header, config) {
});
};
// CLEAR ITEMS
$scope.clearItems = function(){
$scope.list.items.length = 0;
$http.put(API_BASE + 'shopping-lists', $scope.list)
.success(function (data, status, headers, config) {
})
.error(function (data, status, header, config) {
});
};
// CLEAR CHECKED ITEMS
$scope.clearCheckedItems = function(){
var length = $scope.list.items.length-1;
for (var i = length; i > -1; i--) {
if ($scope.list.items[i].isChecked === true) {
$scope.list.items.splice(i,1);
}
}
$http.put(API_BASE + 'shopping-lists', $scope.list)
.success(function (data, status, headers, config) {
})
.error(function (data, status, header, config) {
});
};
//Edit Items / Checked Items
$scope.editItem = function(){
$http.put(API_BASE + 'shopping-lists', $scope.list)
.success(function (data, status, headers, config) {
})
.error(function (data, status, header, config) {
});
};
// SORT ITEMS
$scope.sortBy = function(propertyName) {
$scope.reverse = ($scope.propertyName === propertyName) ? !$scope.reverse : false;
$scope.propertyName = propertyName;
};
}]);
}());
Right now, I can't get the page to load at all. Something isn't being called properly, I just can't figure out how to get the page to load (getting the Filestack to function properly is secondary right now).
Any suggestions with the configuration?
You do not have to declare a module for your controller,
var app = angular.module('myApp');
Change like this also you are missing 'filepickerService' while inecting,
angular.module('myApp').controller('ShoppingListController', ['$scope', '$http','filepickerService', '$routeParams', 'API_BASE', '$location', function($scope, $http, filepickerService, $routeParams, API_BASE, $location){

Preparing http request url in interceptors in AngularJS

I tried to prepare http request url in interceptors rather than adding it to the object passed in $http. Here is the sample of code I tried:
angular.module('myapp', [])
.service('myservice', function() {
this.myfunction = function() {
var req = {method: 'POST', reqName: 'getInfo'};
return $http(req);
}
})
.factory('myInterceptor', function() {
var interceptor = {
'request': function(config) {
config.url = "http://www.myapi.com/demo/"+config.reqName;
return config;
}
}
return interceptor;
})
.config(function($httpProvider) {
$httpProvider.interceptors.push('myInterceptor');
})
But I'm getting an error, which says:
Error: [$http:badreq] Http request configuration url must be a string.
Received: undefined
Any help?
Let me show some tests that proof AngularJS documentation is correct.
Some details about Interceptor - http://docs.angularjs.org/api/ng/service/$http#interceptors
angular.module('myApp', [])
.service('service', function($http) {
this.myfunction = function() {
var req = {
method: 'POST',
reqName: 'getInfo'
};
return $http(req);
}
})
.factory('myInterceptor', function() {
var interceptor = {
'request': function(config) {
config.url = "http://www.myapi.com/demo/" + config.reqName;
return config;
}
}
return interceptor;
})
.config(function($httpProvider) {
$httpProvider.interceptors.push('myInterceptor');
})
describe("myApp", function() {
beforeEach(module("myApp"));
it("executes intercpetor that changes request", inject(function(service, $httpBackend) {
$httpBackend.expectPOST("http://www.myapi.com/demo/getInfo").respond(201, []);
service.myfunction().then(function(r) {
expect(r.config.url).toBe('http://www.myapi.com/demo/getInfo')
})
$httpBackend.flush();
}));
});
<link href="//safjanowski.github.io/jasmine-jsfiddle-pack/pack/jasmine.css" rel="stylesheet" />
<script src="//safjanowski.github.io/jasmine-jsfiddle-pack/pack/jasmine-2.0.3-concated.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular-resource.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular-mocks.js"></script>

routing angularjs cannot get/

Here is my home.html:
<ion-view view-title="Home">
<ion-content>
<h1>here is home </h1>
</ion-content>
</ion-view>
here my app.js:
// Ionic Starter App
// angular.module is a global place for creating, registering and retrieving Angular modules
// 'starter' is the name of this angular module example (also set in a <body> attribute in index.html)
// the 2nd parameter is an array of 'requires'
// 'starter.services' is found in services.js
// 'starter.controllers' is found in controllers.js
angular.module('starter', ['ionic','ionic.service.core', 'starter.controllers', 'starter.services','ui.bootstrap'])
.run(function($ionicPlatform) {
$ionicPlatform.ready(function() {
// Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
// for form inputs)
if (window.cordova && window.cordova.plugins && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
cordova.plugins.Keyboard.disableScroll(true);
}
if (window.StatusBar) {
// org.apache.cordova.statusbar required
StatusBar.styleDefault();
}
});
})
.config(function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('app', {
url: '/app',
abstract: true,
templateUrl: 'templates/menu.html'
})
.state('app.home', {
cache:false,
url: '/home',
views: {
'menuContent': {
templateUrl: 'templates/home.html',
controller: 'homeCtrl'
}
}
})
.state('app.login', {
url: '/login',
views: {
'menuContent': {
templateUrl: 'templates/form-connection.html',
controller: 'LoginConnect'
}
}
})
.state('app.registre', {
url: '/registre',
views: {
'menuContent': {
templateUrl: 'templates/registre.html',
controller: 'registreCtrl'
}
}
})
.state('app.facturer', {
url: '/facturer',
views: {
'menuContent': {
templateUrl: 'templates/facturer.html',
controller: 'facturerCtrl'
}
}
})
.state('app.params', {
url: '/params',
views: {
'menuContent': {
templateUrl: 'templates/parametres.html',
controller: 'parametresCtrl'
}
}
})
.state('app.documents', {
url: '/documents',
views: {
'menuContent': {
templateUrl: 'templates/documents.html',
controller: 'documentsCtrl'
}
}
});
// if none of the above states are matched, use this as the fallback
$urlRouterProvider.otherwise('/app/home');
});
and here my index.html :
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
<title></title>
<link href="lib/ionic/css/ionic.css" rel="stylesheet">
<link href="css/style.css" rel="stylesheet">
<!-- IF using Sass (run gulp sass first), then uncomment below and remove the CSS includes above
<link href="css/ionic.app.css" rel="stylesheet">
-->
<!-- ionic/angularjs js -->
<script src="lib/ionic/js/ionic.bundle.js"></script>
<script src="lib/angular-ui-bootstrap/dist/ui-bootstrap.js"></script>
<link rel="stylesheet" href="lib/angular-ui-bootstrap/dist/ui-bootstrap-csp.css">
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular-messages.js"></script>
<link rel="stylesheet" href="lib/angular-ui-bootstrap/dist/bootstrap.min.css">
<link rel="stylesheet" href="lib/angular-ui-bootstrap/dist/bootstrap-theme.min.css">
<script src="lib/ionic-platform-web-client/dist/ionic.io.bundle.min.js"></script>
<!-- your app's js -->
<!-- ionic/angularjs js -->
<!-- cordova script (this will be a 404 during development) -->
<script src="cordova.js"></script>
<script src="js/app.js"></script>
<script src="js/controllers.js"></script>
<script src="js/services.js"></script>
</head>
<body ng-app="starter">
<ion-nav-view></ion-nav-view>
</body>
</html>
and here the controller :
angular.module('starter', [])
.controller('homeCtrl', function($scope, $stateParams) {
})
.controller('registreCtrl', function($scope, $stateParams) {
})
.controller('facturerCtrl', function($scope, $stateParams) {
})
.controller('documentsCtrl', function($scope, $stateParams) {
})
.controller('parametresCtrl', function($scope, $stateParams) {
})
.config(['$httpProvider', function($httpProvider) {
$httpProvider.defaults.useXDomain = true;
delete $httpProvider.defaults.headers.common['X-Requested-With'];
}
])
//controller pour connection to API
.controller('LoginConnect', ['$scope', 'connecting','sendtoken',
function($scope,connecting,sendtoken){
$scope.user = {};
var users = $scope.user;
$scope.connect = function (users) {
var log = $scope.user.login;
var pass = $scope.user.password;
var mydata = {};
connecting.login(log,pass).then(function(result){
console.log(result);
var montoken = result.data.token;
sessionStorage.setItem('token',montoken);
console.log(montoken);
});
var mytoken = sessionStorage.getItem('token');
console.log(mytoken);
sendtoken.send(mytoken).then(function(userdata){
$scope.datab = userdata;
});
};
}
])
//factory pour aller chercher le token
.factory('connecting', ['$http','$q', function ($http,$q){
var ConnectingFactory = {};
ConnectingFactory.login = function(log,pass){
var deferred = $q.defer();
$http({
method: 'POST',
url: "http://api.tiime-ae.fr/0.1/request/login.php",
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
transformRequest: function(obj) {
var str = [];
for(var p in obj)
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
return str.join("&");
},
data: {login: log, password: pass}
})
.success(function(result){
deferred.resolve(result);
// var promise = deferred.promise;
// promise.then(function(result){
// var mydata = result["data"];
// console.log(mydata);
// }
//);
});
return deferred.promise;
};
return ConnectingFactory;
}])
//END factory pour aller chercher le token
//Factory pour envoyer le token
.factory('sendtoken', ['$http','$q', function ($http,$q){
var tokenreceipt = {};
tokenreceipt.send = function(mytoken){
var deferred = $q.defer();
$http({
method: 'POST',
url: "http://api.tiime-ae.fr/0.1/request/settings-get.php",
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
transformRequest: function(obj) {
var str = [];
for(var p in obj)
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
return str.join("&");
},
data: {token : mytoken}
})
.success(function(userdata){
deferred.resolve(userdata);
// var promise = deferred.promise;
// promise.then(function(result){
// var mydata = result["data"];
// console.log(mydata);
// }
//);
});
return deferred.promise;
};
return tokenreceipt;
}]);
//END Factory pour envoyer le token
;
//envoie du token
// var deferredd = $q.defer();
//
// $http({
// method: 'POST',
// url: "http://api.tiime-ae.fr/0.1/request/settings-get.php",
// headers: {'Content-Type': 'application/x-www-form-urlencoded'},
// data: {token: $scope.user.token}
// })
// .success(function(mesdatas){
// deferredd.resolve(mesdatas);
// var promises = deferredd.promises;
// promises.then(function(mesdatas){
// $scope.datab = mesdatas;
// $scope.user.datab = mesdatas["data"];
// // jsonTab = angular.fromJson(result);
//
//
// });
// })
// console.log($scope.user.token);
//fin envoie token
//user connection
// End of user connection
// .controller('ButtonsCtrl', function ($scope) {
// $scope.singleModel = 1;
//
// $scope.radioModel = 'Middle';
//
// $scope.checkModel = {
// left: false,
// middle: true,
// right: false
// };
//
// $scope.checkResults = [];
//
// $scope.$watchCollection('checkModel', function () {
// $scope.checkResults = [];
// angular.forEach($scope.checkModel, function (value, key) {
// if (value) {
// $scope.checkResults.push(key);
// }
// });
// });
// })
My issue : i got nothing (white page ) when i go to url : http://localhost:8100/home
i only have "Cannot GET /home" and nothing in the console
I'm new in angularJs someone can explain to me my issue ?
You should be going to #/home:
http://localhost:8100/#/home
Try the following url and sure your controller is loading:
http://localhost:8100/#/app/home
Please double check your app.routing.module.ts, there might be a problem on path declaration.

angularjs interceptor $broadcast doesn't work

I'm playing around with the code of
http://ngmodules.org/modules/http-auth-interceptor
and I'm wondering why
$rootScope.$broadcast('loginRequired');
doesn't trigger the alert in the controller
$scope.$on('loginRequired',function() {
alert('loginRequired');
});
The code:
<!doctype html>
<html ng-app="myModule">
<head>
<meta charset="utf-8">
</head>
<body>
<div id="content" class="ng-view"></div>
<script src="http://code.angularjs.org/1.1.5/angular.min.js"></script>
<script>
var buffer = angular.module('http-auth-interceptor-buffer', []);
buffer.factory('httpBuffer', function($injector) {
var buffer = [];
var $http;
function retryHttpRequest(config, deferred) {
function successCallback(response) {
deferred.resolve(response);
}
function errorCallback(response) {
deferred.reject(response);
}
$http = $http || $injector.get('$http');
$http(config).then(successCallback, errorCallback);
}
return {
append: function(config, deferred) {
buffer.push({
config: config,
deferred: deferred
});
},
retryAll: function(updater) {
for (var i = 0; i < buffer.length; ++i) {
retryHttpRequest(updater(buffer[i].config), buffer[i].deferred);
}
buffer = [];
}
};
});
var app = angular.module('myModule', ['http-auth-interceptor-buffer']);
app.config(function($httpProvider,$routeProvider, $locationProvider) {
$httpProvider.interceptors.push('securityInterceptor');
$routeProvider.
when('/one',{
controller: 'OneCtrl',
/*resolve: {
my: function(Data) {
return Data.getData();
}
},*/
templateUrl: './_one.html'
}).
when('/two', {
controller: 'TwoCtrl',
templateUrl:'./_two.html'
})
.otherwise({
redirectTo: '/one'
});
});
app.controller('OneCtrl',function($scope,Data) {
$scope.my = Data.getData();
$scope.$on('loginRequired',function() {
alert('loginRequired');
});
});
app.controller('TwoCtrl',function($scope) {
});
app.factory('Data', function($http,$q) {
return {
getData : function() {
var deferred = $q.defer();
var promise = $http.get('./security.php').success(function (response) {
deferred.resolve(response);
});
// Return the promise to the controller
return deferred.promise;
}
}
});
app.factory('securityInterceptor', function($q, $rootScope,httpBuffer) {
return {
request: function(config) {
return config || $q.when(config);
},
requestError: function(rejection) {
},
response: function(response) {
return response || $q.when(response);
},
responseError: function(rejection) {
if(rejection.status === 401) {
var deferred = $q.defer();
httpBuffer.append(rejection.config, deferred);
$rootScope.$broadcast('loginRequired');
return deferred.promise;
}
return $q.reject(rejection);
}
};
});
</script>
</body>
</html>
UPDATE
security.php
<?php
header('HTTP/1.1 401 Unauthorized');
$data = 'MyTets';
echo json_encode($data);
What's the trouble ?
I tested your code by putting
$rootScope.$broadcast('loginRequired');
in securityInterceptor
response: function(response) {
$rootScope.$broadcast('loginRequired');
return response || $q.when(response);
},
had problem to simulate the response of the php file. Your code and the events are working well. It should come from your php file which didn't return 401 right?
here is a plunker here

angularjs $resource Consuming domainservice error[Error: [ng:areq]] xxxx

**Does anyone know how you can check to see that a resource failed to be fetched in AngularJS?
error:
Error: [ng:areq]
http://errors.angularjs.org/undefined/ng/areq?p0=PhotoListCtrl&p1=not%20a%20function%2C%20got%20undefined
**
<html ng-app>
<head>
<title>angularjs</title>
<link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" />
<script type="text/javascript" src="Scripts/jquery-1.9.1.min.js"></script>
</head>
<body ng-controller="PhotoListCtrl">
<h1>Angular js</h1>
<p>Nothing here {{'yet' + '!'}}</p>
<button title="list" ng-click="list()">list</button>
<button title="copy" ng-click="copy()" >copy</button>
<ul >
<li ng-repeat="photo in photos">
<img src="{{'data:image/png;base64,' + photo.Image}}" title="{{photo.Name}}"></img>
</li>
</ul>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.0-rc.2/angular.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.0-rc.2/angular-resource.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.0-rc.2/angular-route.min.js"></script>
<script type="text/javascript">
var app= angular.module('myApp', ['ngResource']).factory('dataservice', function ($resource) {
return $resource('/applicationdata.svc/Photos/:id', {id:'#id'}, {
query: { method: 'GET', isArray: true },
get: { method: 'GET', params: {id:0} },
remove: { method: 'DELETE' },
edit: { method: 'PUT' },
add: { method: 'POST' }
});
});
app.controller('PhotoListCtrl', ['$scope', 'dataservice', function ($scope, dataservice) {
$scope.photos = [];
$scope.list = function () {
dataservice.query({}, function (data) {
$scope.photos = data.value;
});
};
}]);
//function PhotoListCtrl($scope ,$http) {
// $http.get('/applicationdata.svc/Photos').success(function (data) {
// $scope.photos = data.value;
// });
// $scope.orderProp = 'Name';
// $scope.copy = function () {
// $http.post('/applicationdata.svc/Photos', $scope.photos[0]).success(function (data) {
// console.log(data);
// });
// }
//}
</script>
</body>
</html>

Resources