Using JSON as a service in AngularJS - angularjs

I realise there are a few answers to this question on here, but I just can't seem to get them working with my set up. This is a Plunker of what I am trying achieve (not my own work): http://plnkr.co/edit/Ofq7Md8udEnIhAPF1NgL?p=preview
Currently, I have this for my index.html file:
<body ng-app="HomeCourtArenaApp">
<div class="container" ng-view></div>
<script src="components/angular/angular.js"></script>
<script src="components/require/require.js"></script>
<script src="components/angular/angular-resource.js"></script>
<script src="scripts/services/data.js"></script>
<script src="scripts/app.js"></script>
</body>
To register the components, I have defined them in the karma.conf.js file:
files = [
JASMINE,
JASMINE_ADAPTER,
'app/components/angular/angular.js',
'app/components/angular/angular-resource.js',
'app/components/angular-mocks/angular-mocks.js',
'app/scripts/*.js',
'app/scripts/**/*.js',
'test/mock/**/*.js',
'test/spec/**/*.js'
];
To then create the service, I use the same technique that seems to be documented online in most examples:
'use strict';
angular.module('jsonData', ['ngResource'])
.factory('jsonData', function($resource) {
return $resource('data/shoe3Dconfig.js');
});
Where an error seems to be triggered is when I try to define the service in my 'app' variable, where adding the service name stops the content loading ['jsonData']:
'use strict';
var app = angular.module('HomeCourtArenaApp', ['jsonData']);
app.config(function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'views/main.html',
controller: 'MainCtrl'
})
.otherwise({
redirectTo: '/'
});
});
I would share my views and controllers also, but before I can even use the JSON data in my template, there are an unearthly amount of errors to deal with:
Uncaught Error: Module name "path" has not been loaded yet for context: _. Use require([])
Uncaught Error: Mismatched anonymous define() module: function () {
return getStyleProperty;
}
Uncaught Error: No module: ngResource
There are some other errors also, but these seem to be mainly because the scripts further up the DOM are stopping them loading correctly. Any help would be great!

you could try this :
the app.js:
angular.module('HomeCourtArenaApp', ['HomeCourtArenaApp.services', 'HomeCourtArenaApp.controllers']).
config(['$routeProvider', ($routeProvider) {
$routeProvider.when('/', { templateUrl: 'views/main.html', controller: 'MainCtrl' });
$routeProvider.otherwise({ redirectTo: '/'});
}]);
angular.module('HomeCourtArenaApp.services', ['ngResource']).
factory('JsonData', function($resource){
return $resource('data/shoe3Dconfig.js');
});
angular.module('HomeCourtArenaApp.controllers', []).
controller('MainCtrl', ['$scope', 'JsonData', function($scope, JsonData) {
$scope.objs = JsonData.query();
console.log(objs);
}
}]);
and this is not necessary to load the datas in the html
<script src="scripts/services/data.js"></script>

This edited plunker http://plnkr.co/edit/33qW5VRnQVrHWFlp16kz?p=preview should get you further along the way.
You need to specify the module (jsonData) that you want in your app as a dependency. There is currently no name displayed since your data does not have a name property.
Your JSON service module definition named as 'jsonData'
angular.module('jsonData', ['ngResource'])
This module defines a service provider (factory) 'jsonService'
.factory('jsonService', function($resource) {
You list the 'jsonData' module as a dependency for your module so that you can access anything defined in there
var app = angular.module('plunker', ['jsonData']);
You then use Angular's Dependency Injection to request an instance of jsonService
app.controller('MainCtrl', function($scope, jsonService) {
Note that if you "production-ise" this and minify your JS, you will need to configure the DI code. I will leave that to you to find in the Angular docs.
Does this explain things a bit more?
And you can get the console in plunker by opening the developer tools in your browser.

Related

angular route not working, throw page not found error

in index.html
<script src="lib/angular.min.js"></script>
<script src="lib/angular-route.min.js"></script>
controller
angular.module("testCtrl",[]).controller('TestController', ["$scope", function($scope) {
$scope.Myname = "my first route";
}]);
app.js
var app = angular.module('testApp',["ngRoute", "testCtrl"]);
app.config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider) {
$routeProvider
.when("/",{
templateUrl: "Views/main.html"
})
.when("/details",{
templateUrl: "Views/details.html",
controller : TestController
})
.otherwise({
redirectTo : "/"
});
}]);
my homepage loads fine but with some reason /details show error like --- No webpage was found for the web address: http://127.0.0.1:8080/details
I am new to angular and I am learning. I am not able to understand whats wrong ..do we have any tools to debug route error? I am using angular 1.5.8 version for now.
server console - "GET /details" Error (404): "Not found"
The issue is that TestController isn't defined in app.js. You should use the controller name as a string, like so.
.when("/details",{
templateUrl: "Views/details.html",
controller : "TestController"
})
See this plunk for a working example.
https://plnkr.co/edit/xi20MmchJY6TO1SG2o0d?p=preview
I think you have omitted the dependency on ngRoute:
angular.module('testCtrl', ['ngRoute'])...
Are you referencing ng-app in your HTML as well (can't see your HTML code)
Presumably you have included your scripts in the HTML page too?

Using factories in AngularUI Route?

I'm writing an Ionic app, which uses AngularUI's Router. I'd like to query localstorage using a factory I wrote, so I can determine whether to show a first-run screen or not.
My index.html loads scripts in this order:
<script src="js/app.js"></script>
<script src="js/controllers.js"></script>
<script src="js/services.js"></script>
<script src="js/routes.js"></script>
<script src="js/directives.js"></script>
<script src="js/filters.js"></script>
And my routes config looks like this (truncated for brevity):
angular.module('app.routes', [])
.config(function($stateProvider, $urlRouterProvider, storageFactory) {
$stateProvider
.state('myApp.mainscreen', {
url: '/main',
views: {
'side-menu21': {
templateUrl: 'templates/main.html',
controller: 'mainCtrl'
}
}
})
// ...
$urlRouterProvider.otherwise('/menu/main')
Now I have a module called app.services, which contains my factory, storageFactory (I know, I'm going to move it out of the services module ;)). When I attempt to inject storageFactory like so:
angular.module('app.routes', ['app.services', 'storageFactory'])
.config(function($stateProvider, $urlRouterProvider, storageFactory) {
I get an error similar to this:
Error: [$injector:nomod] Module 'storageFactory' 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.
I'm certain that my app has loaded app.services and storageFactory prior to loading, but I just can't seem to get it to work correctly.
How can I resolve this?
You can inject factories in UI router resolve blocks, without injecting them in the config block since it can only be injected with providers. For example:
$stateProvider
.state('myApp.mainscreen', {
url: '/main',
views: {
'side-menu21': {
templateUrl: 'templates/main.html',
controller: 'mainCtrl'
}
},
resolve: {
firstRun: ['storageFactory', function(storageFactory) {
// Do what you want with storageFactory here!
// Full infos here: https://github.com/angular-ui/ui-router/wiki#resolve
}]
}
})
you cant inject services in config only provides but you can do it in app.run Here's the calling order:
app.config() //only provides can be injected
app.run()
directive's compile functions (if they are found in the dom)
app.controller()
directive's link functions (again, if found)
in your case you can also use route resolve property

Module Injector Error in Angular

I started my first angular application, and am running into an issue where my "home" module isn't working because of a dependency issue. I don't see any dependency missing that I would need. I am using $stateProvider, and $urlProvider, but I am injecting that into the configuration for the home module, so I'm not sure where the problem would lie ?
Config.$inject = ["$stateProvider", "$urlRouterProvider"];
angular.module('home', []).config(Config)
function Config($stateProvider, $urlRouterProvider){
$stateProvider
.state('home', {
url: '/login',
templateUrl: './views/login.html'
})
}
angular.module('home').controller('loginCtrl', function($scope){
$scope.helloWorld = function(){
console.log("This works!")
}
})
The consoled error:
[$injector:modulerr] http://errors.angularjs.org/1.5.5/$injector/modulerr?p0=home&p1=Error%3A%20…
Since "$stateProvider" and "$urlRouterProvider" providers are not part of the core AngularJS module, you need to inject modules, that have this provides into your home module definition. As far as I know, $stateProvider is from ui router module, so
angular.module('home', ['ui.router']).
...
Keep in mind that you also need to include this Javascript in your HTML file. It is in the angular-ui-router file
<script src="js/angular-ui-router.min.js"></script>

How to load REST resources in Angular-Seed bootstrap project from a JEE7 back-end

I am trying to learn hot to invoke a RESTful service that I've implemented in JEE7. I am using the bootstrap template Angular-Seed and the file structure in the tutorial I am using looks a bit different. What I can't seam to figure out is how the $routeProvider and controller relate to each other.
The file structure I have look like this and is similar to the current Angular-Seed structure.
app/
bower_components/
components/
view1/
view1.html
view1.js
view1_test.js
view2/
view2.html
view2.js
view2_test.js
app.css
app.js
controller.js
service.js
index.html
index-async.html
Include the service and the controller in the index.html.
<script src="bower_components/angular-resource/angular-resource.js"></script>
<script src="services.js"></script>
<script src="controller.js"></script>
Added reference to the mainCtrl in app.js
'use strict';
// Declare app level module which depends on views, and components
angular.module('myApp', [
'ngRoute',
'myApp.view1',
'myApp.view2',
'myApp.version'
]).
config(['$routeProvider',
function ($routeProvider) {
$routeProvider.
when('/view1', {
templateUrl: 'view1/view1.html',
controller: 'mainCtrl'
})
}]);
In the services.js file I've declared the invocation of the RESTful service.
var tweetObsService = angular.module('tweetObsService', ['ngResource']);
tweetObsService.factory('tweetFactory', function($resource){
return $resource('http://localhost:8080/bongo-obs/rest/tweets/findAll', {}, {
query: {
method:'GET',
params: {},
isArray:true}
});
});
In the root file controller.js I've declared the mainCtrl.
angular.module('myApp')
.controller('mainCtrl', function($scope, tweetFactory) {
$scope.tweets = {};
tweetFactory.query().$promise.then(function(tweets) {
$scope.tweets = tweets;
});
});
The JSON that the service retrieves has the following structure.
[
{
"id": {
"timestamp": 1454579718,
"machineIdentifier": 12550416,
"processIdentifier": 6912,
"counter": 6510561,
"time": 1454579718000,
"date": 1454579718000,
"timeSecond": 1454579718
},
"userId": 0,
"status": null,
"user": {
"id": 291655833,
"name": "Anders Anderson",
"screenName": "Superuser",
"location": "Sweden",
...
Lats but not least, I tried to render result from the REST service in the view1/view1.html.
<table>
<tr ng-repeat="tweet in tweets">
<td>{{tweet.user.screenName}}</td>
</tr>
</table>
I've no alter the project thanks to submitted answer but I get an error related to the $injector
Error: [$injector:unpr] Unknown provider: tweetFactoryProvider <- tweetFactory <- mainCtrl
http://errors.angularjs.org/1.4.9/$injector/unpr?p0=tweetFactoryProvider%20%3C-%20tweetFactory%20%3C-%20mainCtrl
at http://localhost:8383/mobile-clear-obs/bower_components/angular/angular.js:68:12
at http://localhost:8383/mobile-clear-obs/bower_components/angular/angular.js:4346:19
at Object.getService [as get] (app/bower_components/angular/angular.js:4494:39)
at http://localhost:8383/mobile-clear-obs/bower_components/angular/angular.js:4351:45
at getService (app/bower_components/angular/angular.js:4494:39)
at invoke (app/bower_components/angular/angular.js:4526:13)
at Object.instantiate (app/bower_components/angular/angular.js:4543:27)
at http://localhost:8383/mobile-clear-obs/bower_components/angular/angular.js:9395:28
at link (app/bower_components/angular-route/angular-route.js:977:26)
at invokeLinkFn (app/bower_components/angular/angular.js:9039:9) (09:47:06:656 | error)
How do I correctly injection my mainCtrl, so I can use it in view1.html?
EDIT: Alter the question in response to the submitted.
2.
FINAL EDIT I finally got there with help from niklas. The last problem I stumbled upon is cross domain referencing, resulting in No 'Access-Control-Allow-Origin' header is present on the requested resource. If your backend is running on another server (still localhost), you have to allow cross domain calls to your back-end. Read this post how to solve this problem in JAX-RS 2.
The app.js
// Declare app level module which depends on views, and components
angular.module('myApp', [
'ngRoute',
'myApp.view1',
'myApp.view2',
'myApp.version',
'tweetObsService'
]).
config(['$routeProvider',
function ($routeProvider) {
$routeProvider.
when('/view1', {
templateUrl: 'view1/view1.html',
controller: 'mainCtrl'
})
}]);
The controllers.js
angular.module('myApp')
.controller('YourView1Controller', function($scope, tweetFactory) {
$scope.tweets = {};
tweetFactory.query().$promise.then(function(tweets) {
$scope.tweets = tweets;
}
}
For the view you can then access your desired data like
{{tweets.user.screenName}}and so on
To access the tweetFactory you have to declare the module tweetObsService. with the rest of the modules in myApp.
angular.module('myApp', [
'ngRoute',
'myApp.view1',
'myApp.view2',
'myApp.version',
'tweetObsService' //add this line
]). ...
Make sure your services.js is included in your index.html (some starter projects do it automatically...)

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;
});

Resources