AngularJS eager loading json file - javascript

I am new to angularJS. Sorry, If I am not clear with the question.
Here's the issue.
I have a JSON file ranging 20KB in size. When I try to load this file using 'factory' method, I am getting null value.
var app = angular.module('moonApp', []);
app.factory('MainSource', ['$http', function($http){
var data={source:null};
$http.get('/datafile.json',function(output){
data.source=output;
console.log(data.source); // it works
});
return data;
}]);
app.controller('appCtrl',['$scope','MainSource',function($scope,MainSource){
console.log(MainSource.source); // Not works - getting Null value
}]);
For the above code I am getting NULL value in the console. But If i try it inside the $http success method, it renders the json file contents.
Please help me. Thanks in advance.

I am using $resource to read json file. The following code can load a json file for you.
var app = angular.module('moonApp', ['ngResource']);
app.module('moonApp')
.service('MainSource', function($resource) {
return $resource('/datafile.json', {}, {
query: {
method: 'GET',
isArray: true
}
});
})
Now, inject and use the service in controller
app.controller('appCtrl',['$scope','MainSource',function($scope,MainSource){
MainSource.query(function (data) {
$scope.source = data;
console.log($scope.source); // hopefully you'll see the JSON data here
});
}]);

You can define a function on your MainSource factory and return a promise which you are able to resolve in your controller with the then() call. Please give this a try.
app.factory('MainSource', ['$http', function ($http) {
function getSource() {
return $http.get('/datafile.json', function () {
});
}
return {
'getSource': getSource
}
}]);
app.controller('appCtrl', ['$scope', 'MainSource', function ($scope, MainSource) {
MainSource.getSource().then(function (response) {
console.log(response);
});
}]);

Try like this:
console.log(MainSource.data.source);

Related

How to store data in angularjs application?

Hi I am developing my first Angularjs application. I want to save data in Angularjs application for later use(I have used localstorage in jquery before).
For example, I will make ajax call and i will get some data, Lets say below example,
$http.post('http://192.168.0.213:1234/api/VerifyUser', $stateParams.pageList).then(function (response) {
alert(response.data);
another example, After succesfull login i will get some ID in response and i want to preserve this data all over the application. This ID i may use in all subsequent ajax calls.
I will get some data in response and i want to make use that data in other controllers as well. Is there any way i can do this? any help would be appreciated. Thank you.
you can store it in factory like below,
After your Ajax call
$http.post('http://192.168.0.213:1234/api/VerifyUser', $stateParams.pageList).then(function (response) {
alert(response.data)
SomeFactory.setData(response.data);
};
SomeFactory
(function () {
'use strict';
angular
.module('app.myApp')
.factory('SomeFactory', SomeFactory);
SomeFactory.$inject = [];
function SomeFactory() {
var someData;
var factory = {
setData: setData,
getData: getData
};
function setData(data) {
someData = data;
}
function getData() {
return someData;
}
return factory;
}
})();
In your Controllers
inject your factory to your controller and then getdata
(function () {
'use strict';
angular
.module('app.login')
.controller('LoginController', LoginController);
LoginController.$inject = ['SomeFactory'];
function LoginController(SomeFactory) {
var vm = this;
vm.someVariable = SomeFactory.getData();
console.log(vm.someVariable); // logs your data
}
})();
Sharing data between controllers can be achieved with the following options :
Factory
Service
Then you can inject the service across the controllers and use the data whenever you need.
app.service('myService', function($http) {
this.getJSON = function() {
$http.post('http://192.168.0.213:1234/api/VerifyUser', $stateParams.pageList).then(function(response) {
return response.data;
});
};
});
In Controller:
app.controller('myController', function($scope, myService) {
myService.getJSON().then(function(data) {
$scope.myData = data;
console.log(data);
});
});
DEMO
Use Service to store the data and get the data in another controller later on.
When you inject a Service, it's the same service in every controller - so you can access the properties and methods in that service all over.
https://docs.angularjs.org/guide/services
Example:
.service('YourService', function(){
var YourService = {};
YourService.yourvar = '';
return YourService;
})
.controller('controller1', function($scope, YourService){
YourService.yourvar = 'blah';
})
.controller('controller2', function($scope, YourService){
$scope.currentYourVar = YourService.yourvar;
})

Cannot get data from service after migrating to AngularJS 1.6.3

After migrating to AngularJS 1.6.3, I changed my services like below:
Here is my service:
MetronicApp.factory('MyService', ['$http', function($http) {
return {
get: function(id, success, error) {
return $http.get(baseUrl + '/quotation/' + quotationid).then(success,error);
}
}
}]);
and in ui-router, I'm resolving the data like this.
data: function(MyService, $stateParams) {
return MyService.get($stateParams.id);
}
But in the controller, data comes undefined. Where am I wrong?
It is because you're not returning anything from success/error callback functions. Rather I'd suggest to remove .then(success,error); from get method. and then just call service get method
from resolve.
data: function(MyService, $stateParams) {
return MyService.get($stateParams.id);
}
We are using the following code in the service part just:
get: function(){
return $http.get(url);
}
without any callbacks applied, and in the calling code:
service.someMethod().then(function (result) {
var data = result.data;
}

Need help on Angular Factory

Hi SO angular community !
I'm very confused, I think I have understand the factory purpose and concept, but seems not ...
Here is my problem (surely simple for you) :
I want to use my REST API (working perfectly) using Angular and .factory ...
rest.js
var app = angular.module('urlShortener', ['ngRoute', 'ngResource']);
app.factory('API', ['$resource',
function($resource){
return $resource('/link'});
}],{
get: {method:GET},
post: {method:POST},
put: {method:PUT},
delete: {method:DELETE},
}
);
app.controller('GetAll', function ($scope) {
$scope.links = API.get();
});
index.ejs
<div ng-controller="GetAll">
<ul>
<li ng-repeat="link in links">
<p>{{link.itemId}} --> {{link.url}}</p>
</li>
</ul>
</div>
Not working ... 2 hours I'm consulting the Angular API, and no solutions :/
Please help me I'm wasting time :'(
\\\\ SOLUTION ////
rest.js
app.factory('API', ['$resource', function($resource) { return $resource('/link'); }]);
app.controller('GetAll', ['$scope', 'API', function ($scope, API) {
API.query().$promise.then(function(links) {
$scope.links = links;
});
}]);
Thanks to #dfsq help :)
You can't just assign $resource instance to $scope.links, you need to do it when underlying promise resolves:
app.controller('GetAll', ['$scope', 'API', function ($scope, API) {
API.get().$promise.then(function(links) {
$scope.links = links;
});
}]);
You have to inject "API" in your controller.
app.controller('GetAll', function ($scope, API) {
$scope.links = API.get();
});
If your rest service returns an array of objects you need to use query function.
$scope.links = API.query(); // instead of API.get()
If you need to do anything else when the promise returns use something like this:
API.query().$promise.then(function(result){
$scope.links = result;
// any other operation related to the request here
});
if you want to do api requests, use $http
this is a piece of code I use in my app:
angular
.module('myApp')
.factory('apiFactory', apiFactory);
function apiFactory($http) {
return {
getDataFromApi: getDataFromApi,
};
function getDataFromApi(url) {
return $http({
method: 'GET', // or post or whatever
url: url,
headers: {
...
}
})
.then(success)
.catch(fail);
function success(response) {
return response.data;
}
function fail(response) {
// handle error
}
}
}
Is this what you are looking for?
API For Resources
services.factory('Api', ['$resource',
function($resource) {
return {
Recipe: $resource('/recipes/:id', {id: '#id'}),
Users: $resource('/users/:id', {id: '#id'}),
Group: $resource('/groups/:id', {id: '#id'})
};
}]);
function myCtrl($scope, Api){
$scope.recipe = Api.Recipe.get({id: 1});
$scope.users = Api.Users.query();
...
}

Angular-UI-Router - getting content of dynamic template

I am building an angular app using angular-ui-router. The backend has a REST api that gives me the url to a form based on a ticket id. In app.js, I want to dynamically set the template based on a query to this REST service. Example:
$stateProvider
.state('form', {
url: '/form/:id',
templateProvider: function ($resource, formResolver, $stateParams) {
//formResolver calls the REST API with the form id and gets back a URL.
return formResolver.resolve($stateParams.id).then(function(url) {
return $resource(url).get();
};
},
controller: 'MyCtrl'
});
The problem is that I end up returning a promise and templateProvider requires a string of content. What I would like to do is just return the url:
$stateProvider
.state('form', {
url: '/form/:id',
//I would like to inject formResolver, but I can't
templateUrl: function (stateParams, formResolver) {
return formResolver.resolve(stateParams.id);
},
controller: 'MyCtrl'
});
But I don't get dependency injection when using templateUrl instead of templateProvider as per https://github.com/angular-ui/ui-router/wiki#wiki-templates, and I still have the problem of it returning a promise. I am thinking maybe my only solution is not to use the promise api.
Turns out there was something wrong with the way I was using $resource. I'm still not sure what. From looking at the source for angular-ui-router, the function can return a promise. I ended up copying some of the code from https://github.com/angular-ui/ui-router/blob/master/src/templateFactory.js to get the following, which works:
templateProvider: function ($http, formService, $stateParams) {
return formService.getFormUrl($stateParams.id).then(function(url) {
return $http.get(url);
}).then(function(response) {
return response.data;
})
Function for templateProvider may return promise from $resource but in the end it has to return string.
templateProvider: function (SomeService) {
var promise = SomeService.get().$promise;
promise.then(function (data) {
console.log(data) // it has to be string!
});
return promise;
}
If there is an object one of the solutions would be to make another promise.
templateProvider: function (SomeService, $q) {
var defer = $q.defer();
var promise = SomeService.get().$promise;
promise.then(function (data) {
console.log(data) // let say this is {html: '<p>some template</p>'}
defer.resolve(data.html);
});
return defer.promise;
}
SomeService returns $resource.

Reading in JSON through Angular Resources Service

How can I use angular-resources.js to read in a JSON file through a service?
I am working on a very basic Angular app for testing purposes and am just trying to read in data from JSON file right now. I am placing this code in a service so I can more easily swap it out when we move a server based data store.
My App and App.controller declaration are as follows:
'use strict';
// create module for custom directives
var App = angular.module('App', ['jsonService']);
// controller business logic
App.controller('AppCtrl', function AppCtrl($scope, JsonService) {
console.log("marker 1");
if (!$scope.jsonData) {
console.log("marker 2");
JsonService.getData(function (d) {
console.log(d);
$scope.jsonData = d;
$scope.records = d.length;
});
} else {
console.log("I have data already... " + $scope.jsonData);
}
console.log($scope.jsonData);
});
My JsonService is defined as the follow, at the moment:
'use strict';
angular.module('jsonService', ['ngResource'])
.factory('JsonService', function($resource, $filter) {
// define the remote service using Angular's $resource module
var service = $resource('/data/ProcessModeling-Resources.json', {});
var JsonService = {
// calls $resource.query() to retrieve the remote data.
getData : function getData(callback) {
console.log("marker 3");
service.query(function (data) {
console.log("marker 4");
});
}
};
return JsonService;
});
The console output I am getting follows:
marker 1 app.js:8
marker 2 app.js:11
marker 3 services.js:13
undefined app.js:21
TypeError: Object #<Resource> has no method 'push'
at copy (http://127.0.0.1:8000/lib/angular.js:556:21)
at new Resource (http://127.0.0.1:8000/lib/angular-resource.js:330:9)
at http://127.0.0.1:8000/lib/angular-resource.js:386:32
at forEach (http://127.0.0.1:8000/lib/angular.js:117:20)
at http://127.0.0.1:8000/lib/angular-resource.js:385:19
at wrappedCallback (http://127.0.0.1:8000/lib/angular.js:6650:59)
at http://127.0.0.1:8000/lib/angular.js:6687:26
at Object.Scope.$eval (http://127.0.0.1:8000/lib/angular.js:7840:28)
at Object.Scope.$digest (http://127.0.0.1:8000/lib/angular.js:7707:25)
at Object.Scope.$apply (http://127.0.0.1:8000/lib/angular.js:7926:24) angular.js:5582
I'm receiving my error when I attempt to call my service.query(function (data) { }, which (if I'm understanding correctly) should be pulling my JSON file in.
I've been using AngularJS Cats App as an example for pulling data.
I'd follow #pkozlowski's advice and make sure the response is an array. Anyway, here's an example that loads data from a JSON file similar to what you describe in your comments. It uses ngResource and can help you put things together: http://plnkr.co/edit/Ofq7Md8udEnIhAPF1NgL?p=preview
The service
angular.module('jsonService', ['ngResource'])
.factory('JsonService', function($resource) {
return $resource('cats.json',{ }, {
getData: {method:'GET', isArray: false}
});
});
Notice that isArray is set to false.
Your app and controller
var app = angular.module('app', ['jsonService']);
app.controller('ctrl', function($scope, JsonService){
JsonService.getData(function(data){
$scope.name = data.name;
$scope.children = data.children;
});
});
getData is actually not needed since the Resource class gives you some useful convenience methods such a get, you can just do this
angular.module('jsonService', ['ngResource'])
.factory('JsonService', function($resource) {
return $resource('cats.json');
});
app.controller('ctrl', function($scope, JsonService){
JsonService.get(function(data){
$scope.name = data.name;
$scope.children = data.children;
});
});

Categories