Using factory in another factory is undefined - AngularJS - angularjs

I have a factories called ReportService and IndexService. I want to use IndexService inside of ReportService.
But in ReportService, it says that the IndexService is undefined. I'm not quite sure why.
Here's my code so far:
indexService.js
angular.module('IndexService', []).factory('IndexService', ['$http', function ($http) {
return {
// Sending npm config from server (node) to front-end as JSON so we can use it in front-end.
// See localhost.json.
getConfig: function() {
return $http.get("/api/get-config");
}
}
}]);
reportService.js
angular.module('ReportService', []).factory('ReportService', ['$http', 'IndexService', function ($scope, $http, IndexService) {
// Sending npm config from server (node) to front-end as JSON so we can use it in front-end.
// See localhost.json.
IndexService.getConfig()
.then(function(response) {
var configs = response.data
});
return {
generateExcelReport: function(searchCriteriaList) {
var requestConfig = {
responseType: "arraybuffer",
headers: { "Content-Disposition": "attachment" }
};
// I want to call IndexService.getConfig()
// so I can change my base URL and port based on environment. My configs are in node.js back-end
var url = configs.url;
var port = configs.port;
return $http.post(url + ":" port + "/my-api-link", searchCriteriaList, requestConfig);
},
}
}]);
app.js
angular.module('myApp', ['ngStorage', 'ngRoute', 'appRoutes', 'IndexController', 'IndexService', 'ReportController', 'ReportService', 'PackageController', 'PackageService', 'FarmService', 'DesignService', 'UserService', 'oitozero.ngSweetAlert', 'ui.select', 'ui.materialize', 'ngSanitize', 'ngFileSaver'])
my index.html script imports
<!-- Our Angular Controllers and Services JS -->
<script src="./js/controllers/indexController.js"></script>
<script src="./js/controllers/reportController.js"></script>
<script src="./js/controllers/nerdController.js"></script>
<script src="./js/controllers/packageController.js"></script>
<script src="./js/services/indexService.js"></script>
<script src="./js/services/reportService.js"></script>
<script src="./js/services/farmService.js"></script>
<script src="./js/services/packageService.js"></script>
<script src="./js/services/designService.js"></script>
<script src="./js/services/userService.js"></script>
<script src="./js/appRoutes.js"></script>
<script src="./js/app.js"></script>
Kindly help. I've been over 2 hours on this and I can't still find the problem.. Thanks in advance :)

You need to inject it first, like:
angular
.module('ReportService')
.factory('ReportService', ReportService);
ReportService.$inject = ['IndexService'];
function ReportService(IndexService) {
// You code blah blah here
}
At least this is a way, how i am doing.

Related

Tried many ways still not showing HTML content in ui-grid Angular

In a real-life project, I'm trying to populate an Angular ui-grid using WebAPI to get JSON data has HTML content. So far, the column has HTML is either showing them as plain text or blank content.
Followed this still not getting it work:
How to render html formatted content in ng-grid?
Here are my code:
Index.html (script are downloaded to local)
<script type="text/javascript" src="/scripts/jquery-1.7.2.min.js"></script>
<script src="/scripts/angular-1.5.0.js"></script>
<script src="/scripts/angular-touch-1.5.0.js"></script>
<script src="/scripts/angular-animate-1.5.0.js"></script>
<script src="/scripts/angular-sanitize-1.5.0.min.js"></script>
<script src="/scripts/angular-bind-html-compile.js"></script>
<script src="/scripts/csv.js"></script> <!-- 2013 -->
<script src="/scripts/pdfmake.js"></script>
<script src="/scripts/vfs_fonts.js"></script>
<script src="/scripts/ui-grid.min.js"></script> <!-- v3.2.9-->
<link rel="stylesheet" type="text/css" href="/content/ui-grid.css"/><!-- v3.2.9 - 2016-09-21-->
<script src="/scripts/myAngular.js"></script>
<div ng-controller="getHomeMsg">
<div id="grid1" ui-grid="grdAngHomeMsg" class="Agrid"></div>
</div>
myAngular.js
var myApp = angular.module('app', ['ngTouch', 'ui.grid', 'ngSanitize', 'angular-bind-html-compile']);
myApp.controller('getHomeMsg', function($scope, $http, $sce) // prefix function() with ['$scope', '$http', '$sce', ... got the same result
{
$scope.grdAngHomeMsg = {};
$scope.grdAngHomeMsg.columnDefs = [
{
name: 'Subject',
cellTemplate: '<div class="ui-grid-cell-contents" bind-html-compile="COL_FIELD"></div>' //'<div ng-bind-html="row.entity[col.field]"></div>'
},
{
name: 'Message'
},
];
var msgData;
$http(
{
method: 'GET',
url: '/API/HomeMsg',
responseType: 'json'
}).then(function successCallback(response) {
msgData = $scope.grdAngHomeMsg.data = response.data;
$scope.grdAngHomeMsg.data.forEach(function (d) {
$sce.trustAsHtml(d.Subject); // F12 shows d.Subject has value and valid!
});
}, function errorCallback(response, statusText) {
alert(statusText);
});
// also tried replacing this cellTemplate bind-html-compile="COL_FIELD" with ng-bind-html="AA(COL_FIELD)", F12 shows this function is never called
$scope.AA = function (htm) {
return $sc.trustAsHtml(htm);
};
// it never reach here after actual API call
//msgData.forEach(function (d) {
// $sce.trustAsHtml(d.Subject);
//})
}
);
Browser = FireFox v50.1.
F12 verified data returned are in perfect JSON format.
F12 shows no error during execution, all scripts are loaded, $sce object is instantiated w/ properties including trustAsHtml method.
Other articles/examples tried including:
How do you use $sce.trustAsHtml(string) to replicate ng-bind-html-unsafe in Angular 1.2+
https://github.com/angular-ui/ui-grid/issues/1292
Spent two full days, appreciate any help!

Angular Error: adding dependecy gives $injector:unpr Unknown Provider

I decided to add ngInfinitiScroll plugin to my application. Hence i called the file :
<script type="text/javascript" src="{!! asset('/js/ng-infinite-scroll.min.js') !!}"></script>
In my events.js file i initiated the module like this:
(function(window) {
// Define the `app` module
var app = angular.module('stayhyper', ['infinite-scroll']);
app.controller('eventController', ['$scope', '$rootScope', '$http', 'myService',
function($scope, $rootScope, $http, myService) {
} // end of main function
]); // end of controller
})(window);
Then I get the following error:
Error: $injector:unpr Unknown Provider
Unknown provider: myServiceProvider <- myService<- eventController
MyService (this is in a seperate js file which is loaded in the header):
app.service('myService', function() {
this.URL= function() {
// set the main route of the site
var subhost = "/"
if (window.location.host == "localhost") {
subhost = "/myapp/public/"
}
window.urlRoot = window.location.origin + subhost;//main root of the site
return window.urlRoot;
}
this.APIURL= function() {
// set the main route of the site
var subhost = "/api/"
if (window.location.host == "localhost") {
subhost = "/myapp/public/api/"
}
window.urlRoot = window.location.origin + subhost;//main root of the site
return window.urlRoot;
}
});
You need to load the event.js initially and then mainapp.js , then only the module will be created initially, also make sure you have added the references in html for infinite-scroll
So the order will be,
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/ngInfiniteScroll/1.2.2/ng-infinite-scroll.js"></script>
<script type="text/javascript" src="mainapp.js"></script>
<script type="text/javascript" src="event.js"></script>
also make sure you are not calling the module again.

restangular doesnt return from node-restful API

I am really stuck with this REST API restangular config for my MEAN web application. So I have created the express server with node-restful API and can use POSTMAN to perform CRUD operations and my data is being saved to a MongoDB via Mongoose.
The client side application is a yeoman bootstrap using grunt and I can see hardcoded data in scope if I define it as per below in the controller, however when I attempt to GetList() with Restangular I am having the issue I can see posted previously with returning data from the API Restangular setbaseURL http://localhost:8080/horse.
I understand getList doesn't return data, the factory service is doing this, but I have it set like the examples online and cannot get it to return all records in the MongoDB to the angular view. Also tried ng-resource and I cannot understand why I can't add data from the API to scope.
Code below returns Horsename to "ngview" fine from HorseCtrl using <td>horse in horses</td> table
angular.module('HorseApp')
.controller('HorseCtrl', function ($scope) {
$scope.horses = [
{
horseName: 'MAYKBE DIVA'
}
];
});
below wont return data and my factory is set in app.js
'use strict';
angular.module('HorseApp', ['restangular']);
app.controller('HorseCtrl', function($scope, Restangular) {
$scope.horses = Restangular.all('horses').getList().$object;
});
app.js
'use strict';
angular.module('HorseApp', [
'ngRoute'
'restangular'
])
.config(function ($routeProvider, RestangularProvider) {
RestangularProvider.setBaseUrl('http://localhost:8081/horse');
$routeProvider
.when('/', {
templateUrl: '/views/index.html',
controller: 'HorsesCtrl'
});
})
.factory('HorseRestangular', function(Restangular) {
return Restangular.withConfig(function(RestangularConfigurer) {
RestangularConfigurer.setRestangularFields({
id: '_id'
});
});
})
.factory('Horse', function(HorseRestangular) {
return HorseRestangular.service('horse');
})
I have added the src to index.html as per below, please help :)
<script src="bower_components/jquery/dist/jquery.js"></script>
<script src="bower_components/angular/angular.js"></script>
<script src="bower_components/angular-ui-select/dist/select.js"></script>
<script src="bower_components/bootstrap/dist/js/bootstrap.js"></script>
<script src="bower_components/bootstrap-sass-official/assets/javascripts/bootstrap.js"></script>
<script src="bower_components/angular-resource/angular-resource.js"></script>
<script src="bower_components/restanuglar/dist/restangular.js"></script>
From what I can see, you are globally setting the base url for Restangular to http://localhost:8081/horse, and in your HorseCtrl you are asking Restangular to access the horses endpoint and get the list. This will effectively access the data at http://localhost:8081/horse/horses. I am not sure if this is the intended path.
Your HorseRestangular and Horse factory are not being used. If you were to change the Restangular injection of the controller to Horse, it would access http://localhost:8081/horse/horse, and have the id available through the _id property. You don't necessarily need all of the services unless you will be communicating with more than one API through restangular. To simplify it, you can do this:
angular.module('HorseApp', ['restangular'])
.config(function ($routeProvider, RestangularProvider) {
RestangularProvider.setBaseUrl('http://localhost:8081');
$routeProvider
.when('/', {
templateUrl: '/views/index.html',
controller: 'HorsesCtrl'
});
});
})
.controller('HorseCtrl', function ($scope, Restangular) {
$scope.horses = Restangular.all('horses').getList().$object;
});

Cannot add second AngularJS Service Factory

I try to add 2 Services to my AngularJS Module. One should access my Employees and one my Products, but I get an Unknown provider: EmployeeServiceProvider <- EmployeeService <- BookingController.
All Javascript-Files are added to the html.
App/Module
var coffeewatchApp = angular.module('coffeewatchApp', [
'ngRoute',
'coffeewatchControllers',
'coffeewatchServices'
]);
//Routing
var coffeewatchControllers = angular.module('coffeewatchControllers', []);
var coffeewatchServices = angular.module('coffeewatchServices', []);
EmployeeService.js
var coffeewatchServices = angular.module('coffeewatchServices', ['ngResource']);
var employeeServiceUrlPart = "EmployeeService/";
coffeewatchServices.factory('EmployeeService', ['$resource',
function($resource){
return $resource('all/', {}, {
all: {method:'GET',url:REST_BASEURL+employeeServiceUrlPart+"all", params:{}, isArray:true}
});
}]);
ProductController.js is exactly the same but with Product
var coffeewatchServices = angular.module('coffeewatchServices', ['ngResource']);
var productServiceUrlPart = "ProductService/";
coffeewatchServices.factory('ProductService', ['$resource',
function($resource){
return $resource('all/', {}, {
all: {method:'GET',url:REST_BASEURL+productServiceUrlPart+"all", params:{}, isArray:true}
});
}]);
Controller accessing the two Services
coffeewatchControllers.controller('BookingController', ['$scope', 'EmployeeService', 'ProductService',
function ($scope, EmployeeService, ProductService) {
$scope.employees = EmployeeService.all();
$scope.products = ProductService.all();
}]);
Any help is appreciated; Thanks in advance.
EDIT:
I implemented the EmployeeService first and everything was working great.
So I don't really understand why adding the ProductService kills my EmployeeService. The only thing I can think of is that the ProductService somehow "overwrites" my EmployeeService because it gets injected second.
All added JS-Files in index.html
<script src="js/config/app-config.js"></script>
<script src="js/app.js"></script>
<script src="js/controllers/DashboardController.js"></script>
<script src="js/controllers/StatisticController.js"></script>
<script src="js/controllers/BookingController.js"></script>
<script src="js/services/EmployeeService.js"></script>
<script src="js/services/ProductService.js"></script>
EDITEDIT
After looking at this answer I am even more confused why my code is not working, but maybe the other code will help somone spotting the difference.
In both of your controller files, retrieve the module like this (remove dependency list) -
var coffeewatchServices = angular.module('coffeewatchServices');
Add the dependency to ngResource here instead, while declaring in App/Module -
var coffeewatchServices = angular.module('coffeewatchServices', ['ngResource']);
Your module is getting re-created on the second call in ProductController, so overriding previous module and service definitions.

AngularJS. $resource, MongoLab, Restful API - What's wrong with my sample?

I am new to AngularJS and loving it as I learn it. I am trying to figure out how to communicate with MongoLab from AngularJS using $resource and RESTful API. I have the following two files:
index.html:
-----------
<!DOCTYPE html>
<html lang="en">
<head>
<title>MongoLab Connectivity Test</title>
<script src="angular.js"></script>
<script src="angular-resource.js"></script>
<script src="app3.js"></script>
<link rel="stylesheet" href="bootstrap.css" />
<link rel="stylesheet" href="bootstrap-theme.css" />
</head>
<body ng-app="myModule">
<div ng-controller="display">
<p>{{data.message}}</p>
</div>
</body>
</html>
app3.js:
--------
var myModule = angular.module('myModule', ['ngResource']);
myModule.controller('display', function($scope, personService) {
$scope.data = personService.query();
});
myModule.constant({
DB_BASEURL: "https://api.mongolab.com/api/1/databases/db1/collections",
API_KEY: "<MyAPIKey>"
})
myModule.factory('personService', ['$resource', 'DB_BASEURL', 'API_KEY',
function($resource, DB_BASEURL, API_KEY)
{
return $resource
(DB_BASEURL+'/persons/:id'
,{id: "#id" apiKey: API_KEY}
);
}
]);
When I try it, I get the following output:
{{data.message}}
I am not sure what I am doing wrong. Hoping to get some help.
A better way to connect would be : https://github.com/pkozlowski-opensource/angularjs-mongolab
[copying the text from documentation AS IT IS]
Usage instructions
Firstly you need to include both AngularJS and the angular-mongolab.js script : https://raw.githubusercontent.com/pkozlowski-opensource/angularjs-mongolab/master/src/angular-mongolab.js
Then, you need to configure 2 parameters:
MongoLab key (API_KEY)
database name (DB_NAME)
Configuration parameters needs to be specified in a constant MONGOLAB_CONFIG on an application's module:
var app = angular.module('app', ['mongolabResourceHttp']);
app.constant('MONGOLAB_CONFIG',{API_KEY:'your key goes here', DB_NAME:'angularjs'});
Then, creating new resources is very, very easy and boils down to calling $mongolabResource with a MongoDB collection name:
app.factory('Project', function ($mongolabResourceHttp) {
return $mongolabResourceHttp('projects');
});
As soon as the above is done you are ready to inject and use a freshly created resource in your services and controllers:
app.controller('AppController', function ($scope, Project) {
Project.all().then(function(projects){
$scope.projects = projects;
});
});
Also, you may check out the blog here for even simpler implementation : http://asad.io/angularjs-with-mongolab/
Use the $http module by Angular and Mongolab REST API
For GET request,
$http.get('https://api.mongolab.com/api/1/databases/DATABASE_NAME/collections/COLLECTION_NAME?apiKey=YOUR_API_KEY')
.success(function(data) {
console.log(data)
}
For POST request,
$http.post('https://api.mongolab.com/api/1/databases/DATABASE_NAME/collections/COLLECTION_NAME?apiKey=YOUR_API_KEY', $scope.data, {
headers: {
'Content-Type': 'application/json; charset=UTF-8'
}
})
.success(function() {
console.log('Data saved successfully')
}
More on http method support documentation - http://docs.mongolab.com/data-api/#reference

Resources