I want to inject my service into my controller and just see my console log (in the Auth Service), but I'm getting this error: Argument 'myAppController' is not a function, got undefined. What am I doing wrong?
In my main.js file I have:
var myApp = angular.module('myApp',['ngRoute', 'ui.router']);
myApp.controller('myAppController', ['$scope', function($scope, AuthService) {
console.log('controller');
AuthService.console();
...
In my services.js file I have:
var myApp = angular.module('myApp',[]);
myApp.service('AuthService', function(){
this.console = function(){
console.log('in the AuthService');
}
});
Loading the files in my index.html file as:
<script src="js/main.js"></script>
<script src="js/services.js"></script>
Gotta declare it as a string too for the injection:
myApp.controller('myAppController', ['$scope', 'AuthService', function($scope, AuthService) {
Define MyApp Like this
var myApp = angular.module("myApp", ['ngRoute', 'ui.router']);
myApp.controller('myAppController', function ($scope, ajaxService) {
ajaxService.ajaxGetWithData(url).then(function (data) {
$scope.Data= data;
});
});
app.service('ajaxService', function ($http, $q) {
this.ajaxGetWithData = function (url) {
var deferred = $q.defer();
$http({
method: 'POST', url: url, data: $.param(User),
headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' },
})
.success(function (data) {
if (data != null) {
deferred.resolve(data);
}
})
.error(function (err) {
deferred.reject(err);
});
return deferred.promise;
}
});
Related
I need to call php file using service/Factory method using Angular.js. Here instead of calling $http repeatedly in each file to call diferent php file for different purpose, I need to make it common. I am explaining one example below.
logincontroller.js:
var loginAdmin=angular.module('Takeme');
loginAdmin.controller('loginController',function($scope,$http,$location,$window,inputField){
$http({
method: 'POST',
url: "php/Login/verify.php",
data: userData,
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
}).then(function successCallback(response){
},function errorCallback(response) {
});
}
I have one common route.js file which is common for all controller and given below.
route.js:
var Admin=angular.module('Takeme',['ui.router', '720kb.datepicker','ngMessages','ngCapsLock','ui.bootstrap','ngFileUpload','angularUtils.directives.dirPagination']);
Admin.run(function($rootScope, $state) {
$rootScope.$state = $state;
});
Admin.config(function($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('/');
$stateProvider
.state('/',{
url: '/',
templateUrl: 'view/login.html',
controller: 'loginController'
})
})
Admin.factory('inputField',function($timeout,$window){
return{
borderColor:function(id){
$timeout(function() {
var element = $window.document.getElementById(id);
if(element){
element.focus();
element.style.borderColor = "red";
}
});
},
clearBorderColor:function(id){
$timeout(function() {
var element = $window.document.getElementById(id);
if(element){
element.style.borderColor = "#cccccc";
}
});
}
};
});
Here I need to that $http service to call the php file common for which in every controller I will call that $http repeatedly. I need to pass only the parameters for $http service and return the response.
create a factory/service
angular.module('myApp').factory('DataService', DataService);
DataService.$inject = ['$http', '$q'];
function DataService($http, $q) {
return {
getData: getData,
}
function getData(userData) {
var deferred = $q.defer();
$http({
method: 'POST',
url: "php/Login/verify.php",
data: userData,
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}).then(function(response) {
deferred.resolve(response.data);
},
function(error) {
deferred.reject(error.data);
});
return deferred.promise;
};
}
then use this factory whenever you need in a controller
angular.module('myApp')
.controller('MyController', ['$scope', 'DataService',
function($scope, DataService ) {
$scope.getMyData = function() {
var data = {};
DataService.getData(data)
.then(function(response) {
}, function(error) {
});
};
}
]);
I have created this service.
and using **enrollments.getProperty();**this statement to call this service but it's not working I'm new to angular-JS please let me know where I making the mistake.
var helloAjaxApp = angular.module("myApp", []);
helloAjaxApp.service('enrollments', [ '$scope', '$http', function ($scope, $http) {
$http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded; charset=utf-8";
var enrollments = null;
enrollment();
$scope.enrollment=function () {
$http({
url : 'enrollments',
method : "GET"
}).then(function(response) {
enrollments = response.data;
alert("enrollments");
});
};
return {
getProperty: function () {
return enrollments;
},
setProperty: function(value) {
enrollments = value;
}
};
}]);
use angular.module()
(function () {
'use strict';
angular.module("helloAjaxApp")
.service('enrollments', ['$scope', '$http', function ($scope, $http) {
$http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded; charset=utf-8";
var enrollments = null;
enrollment();
$scope.enrollment = function () {
$http({
url: 'enrollments',
method: "GET"
}).then(function (response) {
enrollments = response.data;
alert("enrollments");
});
};
return {
getProperty: function () {
return enrollments;
},
setProperty: function (value) {
enrollments = value;
}
};
}]);
});
Angular has 2 ways of defining a service: service and factory.
here you can see the difference: https://blog.thoughtram.io/angular/2015/07/07/service-vs-factory-once-and-for-all.html
The basic difference is that service is like a constructor, so you don't return an object from it but define the properties using this keyword:
this.getProperty = function () {
return enrollments;
}
When using the factory method, is expects an object to be returned with the exposed properties/functions.
You are using the factory syntax, so just change the definition to use factory:
helloAjaxApp.factory('enrollments', [ '$scope', '$http', function ($scope, $http)
You should go for a proper service structure like so:
var helloAjaxApp = angular.module("myApp", []);
function EnrollmentService($scope, $http) {
let _this = this;
this.enrollments = null;
this.getEnrollments = function() {
return $http({
url: 'enrollments',
method: 'GET'
}).then(function(response) {
_this.enrollments = response.data;
return _this.enrollments;
})
};
this.setEnrollments = function(enrollments) {
_this.enrollments = enrollments;
}
}
helloAjaxApp.service('enrollments', ['$scope', '$http', EnrollmentService]);
Then, use the service anywhere else:
enrollmentService
.getEnrollments()
.then(function(enrollments) {
// You can use the data here.
console.log(enrollments);
});
The controller code
LoginService is service name you have to pass as a parameter to controller
var loginModule = angular.module('LoginModule',[]);
loginModule.controller('logincontroller', ['$rootScope','$scope','$http','$window','$cookieStore',
'LoginService',logincontrollerFun ]);
function logincontrollerFun($rootScope, $scope, $http, $window,$cookieStore, LoginService,RememberService) {
$scope.loginTest = function() {
LoginService.UserStatus($scope, function(resp) {
console.log("response of login controller ::: ", resp);
///write ur code
});
}
}
service code
var loginModule = angular.module('LoginModule')
loginModule.factory("LoginService",[ '$http', LoginServiceFun ])
function LoginServiceFun($http) {
function UserStatus($scope,callback){
var targetRequestPath='./url';
var targetRequestParamsREQ={'email':$scope.email,'password':$scope.passWord};
return $http({
method: 'POST',
url: targetRequestPath,
headers: {'Content-Type': 'application/json'},
data: targetRequestParamsREQ
}).then(function (response){
console.log('Response Data : ', response.data);
callback( response.data );
})
}
return {
UserStatus:UserStatus
}
}
Here are my code -
var app = angular.module('chartApp', []);
app.controller('artistCtrl', ['$scope', '$http', function($scope, $http) {
$scope.artists =
$http({
method: 'GET',
url: 'http://ws.audioscrobbler.com/2.0/?method=chart.gettopartists',
params: {api_key: 'e8452c5962aafbb3e87c66e4aaaf5cbf', format: 'json'}
}).success(function(result) {
return result.data;
});
console.log($scope.artists);
}]);
How to view the original data from json file?
Move the assignment statement inside the success block:
.success(function(result) {
$scope.artists = result.data;
})
Also, one more thing to note is the console.log($scope.artists) statement right after the $http block will still print undefined because it is executed before the promise is resolved.
Try this it will work :
var app = angular.module('chartApp', []);
app.controller('artistCtrl', ['$scope', '$http', function($scope, $http) {
$scope.artists =
$http({
method: 'GET',
url: 'http://ws.audioscrobbler.com/2.0/?method=chart.gettopartists',
params: {api_key: 'e8452c5962aafbb3e87c66e4aaaf5cbf', format: 'json'}
}).success(function(result) {
$scope.artists = result.data;
}).error(function(msg) {
$scope.err = msg;
});
}]);
I am trying to do a test app based on app from tutorial https://docs.angularjs.org/tutorial/step_00 . It works fine but I have with post method.
index.html
...
<div class="control_panel" ng-controller="phonecatControllers">
<button class="btn btn-default" ng-click="chiliSpicy()">Chili!</button>
<button class="btn btn-default" ng-click="sendData()">send!</button>
</div>
...
controllers.js
'use strict';
var phonecatControllers = angular.module('phonecatControllers', []);
phonecatControllers.controller('PhoneListCtrl', ['$scope', '$http', '$log',
function ($scope, $http, $log) {
$http.get('http://localhost:8080/webapp/rest/myresource/posts').
success(function (data) {
$scope.posts = data;
});
$scope.data = "hello world";
$scope.chiliSpicy = function () {
$log.info('chili function');
};
$scope.sendData = function () {
$http.post('http://localhost:8080/webapp/rest/myresource/', {'data' : $scope.data} )
.succes(function (data, status, headers, config) { // !!! here is line 39
$log.info('sent');
})
.error(function (data, status, headers, config) {
$log.error('not sent')
});
};
}]);
Get method works ok (showed html code does not contain its usage), also chiliSpicy function works. But sendData function throws error (where success function is)
TypeError: undefined is not a function
at l.$scope.sendData (http://localhost:8080/webapp/controllers.js:39:18)
at https://ajax.googleapis.com/ajax/libs/angularjs/1.3.8/angular.min.js:198:424
at chrome-extension://ighdmehidhipcmcojjgiloacoafjmpfk/dist/hint.js:798:21
at l.$eval (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.8/angular.min.js:126:84)
at l.$apply (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.8/angular.min.js:126:310)
at l.scopePrototype.$apply (chrome-extension://ighdmehidhipcmcojjgiloacoafjmpfk/dist/hint.js:1478:22)
at HTMLButtonElement.<anonymous> (chrome-extension://ighdmehidhipcmcojjgiloacoafjmpfk/dist/hint.js:797:25)
at HTMLButtonElement.c (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.8/angular.min.js:32:363)
Actually, the server receives data, but success function do not pass. Any idea? Thanks.
Misspelled success, written as succes.
There is typo. It should be success instead of 'succes'
phonecatControllers.controller('PhoneListCtrl', ['$scope', '$http', '$log',
function ($scope, $http, $log) {
$http.get('http://localhost:8080/webapp/rest/myresource/posts').
success(function (data) {
$scope.posts = data;
});
$scope.data = "hello world";
$scope.chiliSpicy = function () {
$log.info('chili function');
};
$scope.sendData = function () {
$http.post('http://localhost:8080/webapp/rest/myresource/', {'data' : $scope.data} )
.success(function (data, status, headers, config) { // !!! here is line 39
$log.info('sent');
})
.error(function (data, status, headers, config) {
$log.error('not sent')
});
};
}]);
I have defined a custom http service in angular that looks like this:
angular.module('myApp')
.factory('myhttpserv', function ($http) {
var url = "http://my.ip.address/"
var http = {
async: function (webService) {
var promise = $http.get(url + webService, { cache: true }).then(function (response) {
return response.data;
});
return promise;
}
};
return http;
});
And I can access this service in my controller like so:
angular.module('myApp')
.controller('myCtrl', function (myhttpserv) {
var webService = 'getUser?u=3'
myhttpserv.async(webService).then(function (data) {
console.log(data);
})
});
However I now need to streamline this process so that it is ALL contained inside the service with a static url and it simply returns the data. So that I can just call it in the controller like so:
angular.module('myApp')
.controller('myCtrl', function ($scope, myhttpserv) {
console.log(myhttpserv.var1);
console.log(myhttpserv.var2);
etc...
});
I can't seem to tweak the service to get this functionality. Anyone know the correct way to do it?
Option 1 - Use promise API
angular.module('myApp').factory('myhttpserv', function ($http) {
return $http.get('http://my.ip.address/getUser?u=3', { cache: true });
});
Controller:
angular.module('myApp').controller('myCtrl', function ($scope, myhttpserv) {
myhttpserv.then(function(response){
console.log(response.data);
});
});
Option 2 - Using route resolve
angular.module('myApp', ['ngRoute']).config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/myCtrl', {
templateUrl: 'myView.html',
controller: 'myCtrl',
resolve: {
load: function (myhttpserv) {
return myhttpserv;
}
});
}]);
Service:
angular.module('myApp').factory('myhttpserv', function ($http) {
var data = {};
var url = "http://my.ip.address/";
var promise = $http.get(url + 'getUser?u=3', { cache: true }).then(function (response) {
data = response.data;
});
return data;
});
Controller:
angular.module('myApp')
.controller('myCtrl', function ($scope, myhttpserv) {
console.log(myhttpserv.data.var1);
console.log(myhttpserv.data.var1);
etc...
});
Option 3 - Use $interval service
angular.module('myApp').factory('myhttpserv', function ($http) {
var data = {};
var url = "http://my.ip.address/";
var promise = $http.get(url + 'getUser?u=3', { cache: true }).then(function (response) {
data = response.data;
});
return data;
});
Controller:
angular.module('myApp').controller('myCtrl', function ($scope, $interval, myhttpserv) {
$scope.intervalPromise = $interval(function(){
if (Object.keys(myhttpserv.data).length!=0)
{
console.log(myhttpserv.data);
$interval.cancel($scope.intervalPromise);
}
}, 100);
});