Angular Service Is Not A Function - javascript

I've created a simple logging service in Angular:
app.service('$userInteraction', [function() {
var userLog = "";
this.log = function (datetime, screen, logMessage) {
userLog.concat(datetime + "\t" + screen + " Screen\t" + logMessage + "\n");
}
this.getLog = function () {
return userLog;
}
this.clearLog = function () {
userLog = "";
}
}]);
And I use it in one of my controllers like so:
app.controller('myController', ['$scope', '$userInteraction', function($scope, $userInteraction) {
$userInteraction.log(Date(), 'Login', 'Some random message.');
}]);
But when I run my code I get the following error:
TypeError: $userInteraction.log is not a function
Though I could've sworn that it worked before. I'm fairly new to Angular so this might very well be a newbie mistake. Thanks in advance!

this question is old, but help someone... You code run on plunker, problably you have duplicate services name... Check all files angularjs and verify if exist another service with same name.
I had similar problem. Two services with same name and call did not have function called.

Related

AngularJS - Extremely confused about how to use $resource actions

I'm very new to AngularJS, and Web Development in general. I would really appreciate some help regarding the actions for client-server interactions and $resource
Here is a small snippet of code from my program
.factory('commentFactory', ['$resource', 'baseURL', function($resource, baseURL) {
var commentFac = {};
comment.getComment= function() {
return $resource(baseURL + "comments/", null);
};
return commentFac;
}])
In the following controller, $scope.feedback elements are being changed with the ng-model directive in the webpage
.controller('FeedbackController', ['$scope', 'commentFactory', function($scope, commentFactory) {
$scope.feedback = {mychannel:"", firstName:"", lastName:"", agree:false, email:"" };
$scope.sendFeedback = function() {
commentFactory.getComment().save(
$scope.feedback, //What I want to send back to the server
function() { //Callback functions. No idea what to put here
},
function() {
}
);
}])
How will $scope.feedback be stored in the server? How would i be able to later access the comments when needed? I'm almost !00% certain my .save action is icorrect, but I can't seem to find online how I'm supposed to use it. What do I put in the callback functions?
I'm sorry that this is such a rookie questions, but this is honestly a little difficult to comprehend.
Edit: I changed the line
return $resource(baseURL + "comments/", null);
to
return $resource(baseURL + "comments/:id", null);
and it worked. I'm not sure why though. Would appreciate an explanation and answers to my above questions.
Thanks again

Can't pass data between controllers?

I don't get what I'm doing wrong, I am trying to globally store and pass data from one controller to another via a service. I stored the data in one controller and confirmed that it was stored at the beginning of my buildReportController. Then, when I click a button on my UI, it opens reportResultsController. However, issue is, I can store the data correctly in buildReportController via locationHistoryService.store() but when I go to reportResultsController and calllocationHistoryService.get(), thepreviousLocationvariable inlocationHistoryService` is empty as if the data was never set. Any ideas on how why or how I can "globally" store data and pass it between controllers? Below is my attempt. Thanks!
In reportView.js
angular.module('reportView', [])
.service('locationHistoryService', function(){
var previousLocation = "";
return {
store: function(location){
previousLocation = location;
},
get: function(){
return previousLocation;
}
};
});
In buildReport.js
angular.module('buildReport', ['reportView'])
.controller('buildReportController', ['$rootScope', 'locationHistoryService'], function($rootScope, locationHistoryService){
$rootScope.$on('$locationChangeSuccess', function(e, newLocation, oldLocation){
locationHistoryService.store(oldLocation);
console.log("Old location: ", oldLocation);
});
}
In reportResults.js
angular.module('reportResults', ['reportView'])
.controller('reportResultsController', ['$rootScope', 'locationHistoryService'], function($rootScope, locationHistoryService){
console.log("location : ", locationHistoryService.get());
}
The locationHistoryService.get() method in reportResults.js is called before it is set in buildReport.js.
It would be better if you announce when the previousLocation variable has been set.
In reportView.js
angular.module('reportView', [])
.service('locationHistoryService',['$rootScope'] ,function($rootScope){
var previousLocation = "";
return {
store: function(location){
previousLocation = location;
$rootScope.$broadcast('previous-location-set');
},
get: function(){
return previousLocation;
}
};
});
In reportResults.js
angular.module('reportResults', ['reportView'])
.controller('reportResultsController', ['$rootScope', 'locationHistoryService'], function($rootScope, locationHistoryService){
$rootScope.$on('previous-location-set', function(){
console.log("location : ", locationHistoryService.get());
});
}
Your webapp should have only one module which is automatically bootstrapped by angular, and other modules as dependencies. The syntax of writing service is incorrect. You wrote .service but returning object which .factory should return. Here is working example of your code http://codepen.io/Chyngyz/pen/NxbdpW?editors=101
Also you wrote the safe for minification syntax of controllers incorrect, the function block of controller should be the last item in the array.

AngularJS $injector:unpr Unknown Provider Error

I am trying to create a user profile page. Where User can display and edit their information.
This is my Controller.js
var userProfileControllers = angular.module("userProfileControllers", []);
userProfileControllers.controller ('userProfileCtrl', ['$scope', '$location', 'localCache', 'customersignup', function ($scope, $location, localCache, customersignup){
var submitProfile = function() {
//Bind Scope
//
var bindScope = function () {
$scope.userProfile = customersignup.userProfile;
};
var asyncBindScope = function() {
$scope.$evalAsync(bindScope());
};
bindScope ();
}}]);
This is my service.js
var userProfileServices = angular.module("userProfileServices", []);
userProfileServices.factory("customersignup", function() {
return {
userProfile: {fname: "kunal"},
updateProfile: function() {
var userProfile = this.userProfile;
},
}
});
In the HTML, let's say in case of first name I have included ng-model="userProfile.fname" in the input of First Name field. Now, when I am loading the html page, I am getting this error :-
https://docs.angularjs.org/error/$injector/unpr?p0=localCacheProvider%20%3C-%20localCache%20%3C-%20userProfileCtrl
Please check the above link, it is from AngularJS official site.
check you have two modules one is for service and other one is for controller, and note that there is no glue between these two modules, to work this you need to glue these two modules, to do that, import the service module in to controller module as below.
var userProfileControllers = angular.module("userProfileControllers", ['userProfileServices']);
then module userProfileControllers have access to module userProfileServices which service is defined. Other vice you don't have access to service module userProfileServices.
You have to add factory name in controller userProfileServices

updating time in angularjs app

In my angularjs app, i define a var for put a "prefix" in my all console.log
var app = angular.module('app', ['ngRoute', 'ngCookies', 'LocalStorageModule', 'ngResource', 'pascalprecht.translate']).run(function($rootScope, $timeout) {
$rootScope.defineCLC = "[ZR Console CL] " + updatingTime() + " ===> ";
[etc ...]
I use $rootScope.defineCLC in my controllers.
For having the time updated, i put in pure js, outside :
function updatingTime() {
setTimeout('updatingTime()', 3000);
var currentTime = new Date();
console.log('ok !');
return currentTime;
}
problem is it's doesnt't work, the time is always the date when app whas executed :/ how to update the time for having it good in the console.log ?
setTimeout('updatingTime()', 3000); will give you an error after 3secs (check the developer console in the browser) since you supply a string instead of a function.
You'll have to make a function and call it with angular's version of setInterval.
var app = angular.module('app', []).run(function($rootScope, $interval) {
var fun = function() {
$rootScope.defineCLC = "[ZR Console CL] " + new Date() + " ===> ";
};
$interval(fun, 3000);
}]);

jasmine, $q is undefined

I'm going through some of the examples online for AngularJS to try to understand how it works. I'm trying to use jasmine to test like in the examples. In my spec file, I have:
var Person = function (name, $log) {
this.eat = function (food) {
$log.info(name + " is eating delicious " + food);
};
this.beHungry = function (reason) {
$log.warn(name + " hungry " + reason);
};
};
var bob = new Person();
describe("describe", function () {
it("$q", function () {
var pizzaOrderFulfillment = $q.defer();
var pizzaDelivered = pizzaOrderFulfillment.promise;
pizzaDelivered.then(bob.eat, bob.beHungry);
pizzaOrderFulfillment.resolve("resolved");
$rootScope.$digest();
expect($log.TypeInfo.logs).toContain(["resolved"]);
});
});
I get
ReferenceError: $q is not defined
Am I using Jasmine correctly? I basically am just writing all my angular and jasmine code in the spec.js file. When I had the angular code in another file, my spec.js file couldn't find it. Probably because I didn't set any dependencies up on what gets loaded first since I'm just starting out with this stuff.
Edit, fixed the $ to be $q and the referencerror.
I guess you are not injecting the $q service in your unit test.
For example in your beforeEach block you can inject it:
var q;
beforeEach(inject(function($q) {
q = $q;
}));
And then in your unit test:
describe("describe", function () {
it("$q", function () {
var pizzaOrderFulfillment = q.defer();
var pizzaDelivered = pizzaOrderFulfillment.promise;
pizzaDelivered.then(bob.eat, bob.beHungry);
pizzaOrderFulfillment.resolve("resolved");
$rootScope.$digest();
expect($log.TypeInfo.logs).toContain(["resolved"]);
});
});

Categories

Resources