Angularjs view not showing, caused by factory - angularjs

I have a problem adding factory functions to my AngularJs module.
When I add the 'authInterceptor' factory function to my home view module. The view isn't loading. But when I delete the factory function it does load.
What am I doing wrong?
Home controller
'use strict';
angular.module('myApp.home', ['ngRoute'])
.factory('authInterceptor', function ($rootScope, $q, $window) {
return {
request: function (config) {
config.headers = config.headers || {};
if ($window.sessionStorage.token) {
config.headers.Authorization = 'Bearer ' + $window.sessionStorage.token;
}
return config;
},
responseError: function (rejection) {
if (rejection.status === 401) {
// handle the case where the user is not authenticated
}
return $q.reject(rejection);
}
};
})
.config(['$routeProvider', function($routeProvider, $httpProvider) {
$httpProvider.interceptors.push('authInterceptor');
$routeProvider.when('/', {
templateUrl: 'home/home.html',
controller: 'HomeCtrl'
});
}])
.controller('HomeCtrl', function($scope, $http, $window) {
console.log("Home Controller");
});
general module loader
// public/js/app.js
angular.module('myApp', [
'ngRoute',
'myApp.home'
])
.config(['$locationProvider', '$routeProvider',
function($locationProvider, $routeProvider, $httpProvider) {
$locationProvider.hashPrefix('!');
$routeProvider.otherwise({redirectTo: '/home'});
}])
.run(function($rootScope, $http){
$rootScope.my_message = 'test';
});

The problem is that your factory has a semi-colon, which breaks the following code.
.factory('authInterceptor', function () {
return 'a12345654321x';
}); //<==== remove this semicolon
//otherwise this breaks
.config(['$routeProvider', function($routeProvider, $httpProvider) {
//etc
}])
Edit for your second problem: You are missing the $httpProvider in your dependencies.
.config(['$routeProvider', function($routeProvider, $httpProvider
=>
.config(['$routeProvider', '$httpProvider', function($routeProvider, $httpProvider

Related

$compile:tpload] http://errors.angularjs.org/1.6.3/$compile/tpload? Unidentified partial in angular eventhough path url is correct

I ran the link on the browser and it worked but it never loads up in the application.
Error in my console:
Error: [$compile:tpload] http://errors.angularjs.org/1.6.3/$compile/tpload?p0=app%2Fviews%2Fpartials%2Fpartial-index.html&p1=undefined&p2=undefined
my app.js:
(function(){
'use strict';
var app = angular.module('app',[
'ui.router',
'ngCookies'
]);
app.config([
'$stateProvider',
'$urlRouterProvider',
'$httpProvider',
'$locationProvider',
'staticData',
authConfig
]);
function authConfig(
$stateProvider,
$urlRouterProvider,
$httpProvider,
$locationProvider,
staticData ) {
$stateProvider.state('index', {
url: '/',
templateUrl: 'app/views/partials/partial-index.html'
});
$locationProvider.html5Mode(true);
$httpProvider.interceptors.push('requestInterceptor');
app.run([
'$rootScope',
'$state',
'authService',
authRun
]);
function authRun($rootScope, $state, authService){
$rootScope.$on('$stateChangeStart', function(event, toState){
if(toState.data && toState.data.accessLevel){
var user = authService.getUserData();
if(!(toState.data.accessLevel & user.role)){
event.preventDefault();
$state.go('index');
return;
}
}
})
}
})();
My directory:

Post method using Asp.Net WebApi controller with AngularJS

Angular controller code:
(function ()
{
myApp.controller("LoginController", function ($scope, $http, $location, $window) {
$scope.Emp = {};
console.log("cont");
$scope.Submit = function (Emp) {
console.log("inside", $scope.Emp);
$http({
method: "POST",
url: '#/Test/Login',
data: $scope.Emp,
})
.then(function successCallback(response) {
console.log("response", response.data);
//$window.location.href = '/Home/Display';
if (response.data == "CORRECT UserName and Password") {
console.log("if condition")
$window.location.href = '/Test/Display';
}
else if (response.data == "INCORRECT UserName") {
alert("INCORRECT UserName or Password");
}
})
}
$scope.Register = function () {
$window.location.href = '/Test/Register';
}
});
})(angular.module('myApp'));
Angular Module Code:
var myApp = angular.module('myapp', ['ngRoute']);
app.config('$StateProvider', '$UrlRouteProvider','$scope', '$LogProvider', '$http', '$location', '$window',
function ($StateProvider, $UrlRouteProvider, $scope, $http, $location, $window)
{
$UrlRouteProvider.otherwise("/Login");
$StateProvider
.state('Login'),{
url:'/Login',
views:{
'#':{
templateUrl: "/Views/Home/Login.cshtml",
controller: 'LoginController'
}
}
}})
You only declared but didn't inject $LogProvider in config after $scope. Declaration and injection have to be same and in exact order as well.
It should be like :
app.config('$StateProvider', '$UrlRouteProvider', '$scope', '$LogProvider', '$http', '$location', '$window',
function ($StateProvider, $UrlRouteProvider, $scope, $LogProvider, $http, $location, $window)
{
$UrlRouteProvider.otherwise("/Login");
$StateProvider
.state('Login'),{
url:'/Login',
views:{
'#':{
templateUrl: "/Views/Home/Login.cshtml",
controller: 'LoginController'
}
}
}})
also there is # in your url: '#/Test/Login', check if you need it.
further, as per your code in question, it seems you don't require these much dependencies in config. In your code, I don't see any use of $scope, $LogProvider, $http, $location, $window..

AngularJS 1 factory error unknowwn provider

I'm trying to get the data from a json file.
i have a file, factory1.js
myApp.factory('mainInfo', [
'$http',
function($http) {
return {
get: function(){
$http.get('data.json');
}
}}])
and then i have another file, view1.js
'use strict';
angular.module('myApp.view1', ['ngRoute'])
.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/view1', {
templateUrl: 'view1/view1.html',
controller: 'View1Ctrl'
});
}])
.controller('View1Ctrl', [
'$scope',
'$http',
'mainInfo',
function($scope, $http, mainInfo) {
mainInfo.get("data.json")
.then(function(response) {
$scope.myWelcome = response.data;
console.log($scope.myWelcome)
});
}]);
i have one folder with each of the json, factory and controller files in it.
when i run this the error it is returning says...
angular.js:13708 Error: [$injector:unpr] Unknown provider: mainInfoProvider <- mainInfo <- View1Ctrl
where am i going wrong?
Working fine. This solves your problem i hope so.
'use strict';
var app=angular.module('myApp.view1', ['ngRoute'])
app.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/view1', {
templateUrl: 'view1/view1.html',
controller: 'View1Ctrl'
});
}])
app.factory('mainInfo',
function($http) {
var obj={};
obj.method =function(){
return $http.get('tag.json')
}
return obj;
})
app.controller('View1Ctrl', [
'$scope',
'$http',
'mainInfo',
function($scope, $http, mainInfo) {
mainInfo.method().success(function(response) {
$scope.myWelcome = response;
});
}]);
var app=angular.module('myApp.view1', ['ngRoute']);
app.factory('mainInfo', [
'$http',
function($http) {
return {
get: function(){
$http.get('data.json');
}
}}])
define one variable and assign your module to that variable and bind the variable to the factory.if you have module with name myApp inject that module in to myapp.view1 module
like
angular.module('myApp.view1', ['ngRoute','myApp'])
Register mainInfo inside Angular module, if it's a different module.
view1.js
angular.module('myApp.view1', ['ngRoute', 'myApp']);
You have not assigned your module to a variable.
var myApp = angular.module('myApp.view1', ['ngRoute']) ...
Then use myApp.factory
myApp.factory('mainInfo', [...
see this plunkr for quick understanding.

Restangular ignores setBaseUrl

The app runs on http://domain1 an must request data from http://domain2 with the following code:
'use strict';
// Declare app level module which depends on views, and components
var myApp = angular.module('myApp', [
'ngRoute',
'restangular'
]);
myApp.config(['$routeProvider', 'RestangularProvider', function($routeProvider, RestangularProvider) {
$routeProvider.when('/view1', {
templateUrl: '/view1.html',
controller: 'View1Ctrl'
});
$routeProvider.otherwise({redirectTo: '/view1'});
RestangularProvider.setBaseUrl("http://domain2/");
}]);
var rest = null;
myApp.controller('View1Ctrl', ['$scope', 'Restangular', function($scope, Restangular) {
rest = Restangular;
var cursos = Restangular.one("resource",100).get()
}]);
Nonetheless, the request goes to http://domain1. What is going on? I also inspected the Restangular configuration, by putting Restangular in the global scope, as the rest variable, and the base url seems is property set.
Hey you can create a factory and use different domain to get data something like below
(function () {
'use strict';
angular.module('app')
.factory('Domain2Restangular', ['Restangular', Domain2RestangularFunction]);
function Domain2RestangularFunction( Restangular) {
return Restangular.withConfig(function(RestangularConfigurer) {
var baseURL = 'http://domain2';
RestangularConfigurer.setBaseUrl(baseURL);
RestangularConfigurer.setDefaultHeaders({'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8' });
});
}
}());
You can invoke
return Domain2Restangular.all('')
.post(data)
.then(function(response) {
return response;
}, function(error) {
return error
});

Uncaught Error: [$injector:cdep] use ngdialog in factory

I want to use ngdialog to do with the 401 status, but I get the error:Uncaught Error: [$injector:cdep]
angular.module('ws.site.master', [
'ngResource',
'ngCookies',
'ngSanitize',
'ngAnimate',
'ui.router',
'ngDialog'
]);
here I add a factory to do with the 401 status.
angular.module('ws.site.master').factory('authHttpResponseInterceptor',['$q','$location','ngDialog',function($q,$location,ngDialog){
return {
response: function(response){
if (response.status === 401) {
console.log("Response 401");
}
return response || $q.when(response);
},
responseError: function(rejection) {
if (rejection.status === 401) {
console.log("Response Error 401",rejection);
ngDialog.open({
template: '/common/templates/at.modal.security.html',
className: 'ngdialog-theme-default modal-security',
closeByDocument: false,
closeByEscape: false,
trapFocus: false,
controller: ['$scope', function($scope) {
$scope.defaultView = defaultView || 'login';
}]
});
$rootScope.isSecurityModal = true;
}
return $q.reject(rejection);
}
}
}]);
here add the authHttpResponseInterceptor to $httpProvider
angular.module('ws.site.master').config(['$stateProvider', '$urlRouterProvider', '$locationProvider', '$httpProvider', 'ROUTE',
function ($stateProvider, $urlRouterProvider, $locationProvider, $httpProvider, ROUTE) {
$locationProvider.html5Mode(true);
angular.forEach(ROUTE, function(_route, _name){
$stateProvider.state(_name, _route);
});
$urlRouterProvider.otherwise('/');
$httpProvider.interceptors.push('authHttpResponseInterceptor');
}
]);
Error: $injector:cdep - Circular Dependency
Please check the angular docs about this
angular.module('myApp', [])
.factory('myService', function (myService) {
// ...
})
.controller('MyCtrl', function ($scope, myService) {
// ...
});
you are injecting 'ngDialog' twice, to you main module and then to factory and all of this is in the same 'ws.site.master'
For dialog window, you have to have bootstrap-tpls included in your html header. And the app should be as follows:
angular.module('myModule', [ 'ui.bootstrap']);
In controller or factory have:
app.controller('myController', function($scope, $modal) {
...
$scope.openPopup = function() {
$scope.modalInstance = $modal
.open({
animation : true,
backdrop : 'static',
templateUrl : 'yourTemplatePath/template.html',
controller : 'yourPopupController'
});
$scope.modalInstance.result.then(function(returnResult) {
$scope.returnResult = returnResult;
});
};

Resources