AngularJS Cannot read property 'getData' of undefined in VS - json

do you know what I am doing wrong? I want to read data from my json-file but i got the error that it canĀ“t read the property getData.
myApp.service('jsonDataService', function ($http) {
this.getData = function () {
return $http({
method: 'GET',
url: '/jsonData/Stations.json'
});
}
});
controller:
myApp.controller('IndexController', ['$scope', function ($scope, jsonDataService) {
jsonDataService.getData().then(function (msg) {
$scope.msg = msg;
console.log(msg);
});
}]);
I am using ng in Visual studio in a mvc project.
path json-file: " Visual Studio 2015\Projects\Test\WebApplication\Scripts\jsonData\Stations.json"

In the controller code which you have shared, you have not injected 'jsonDataService' service properly.
It should be:
myApp.controller('IndexController', ['$scope', 'jsonDataService', function ($scope, jsonDataService) {
jsonDataService.getData().then(function (msg) {
$scope.msg = msg;
console.log(msg);
});
}]);

Related

AngularJS - Using a service to get JSON from server

I'm trying to learn AngularJS and need some help. I'm using version 1.4.9 and I'm trying to create a service that will get JSON from a server but I'm getting the following error: "serviceName is not defined"
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular.min.js"></script>
Here is my service:
app.service('serviceName', function ($http, $q) {
var url= "myURL";
function getData() {
return $http.get(url);
}
return {
getData: getData,
}
}
);
Here is my controller:
app.controller("myController", function ($scope, $http) {
serviceName.getData().then(function (response) {
$scope.myField = response.data;
});
});
You need to inject your service into the controller, like this:
app.controller("myController", function ($scope, serviceName) {
serviceName.getData().then(function (response) {
$scope.myField = response.data;
});
});
And you do not need $http, because that's used in the service ;)

how to define angular methods

I'm a regular consumer of advice from Stackoverflow. It's an invaluable tool - thanks for all the help!
But this is my first question: I'm very new to Angular but I've been doing server side stuff for donkeys years.
I've got a method on a controller, which calls a server REST service. My problem is that the method is called whenever the controller is instantiated. I know there's got to be another way of declaring the function, but I've got no idea of what to search for.
Here's my html:
<html lang="en" data-ng-app="mLS" ng-controller="mLSController">
<head>....</head>
...
<li><a ng-if="userName" ng-click="Logout()">logout</a></li>
and my module (the module def is elsewhere, but it seems ok)
var app = angular.module('mLS');
app.controller('mLSController', function ($scope, $http, $window, $location) {
$http({
url: '/api/UI/GetUsername',
method: 'GET'
}).success(function (data, status, headers, config) {
$scope.userName = data;
$scope.desiredPath = $location.path();
if (!$scope.userName && $scope.desiredPath != '/Account/Login')
$window.location.href = '/Account/Login';
});
});
function Logout($http) {
$http({ url: '/api/UI/Logout', method: 'GET' });
}
//app.
// controller('mLSController', function ($scope, $http) {
// $scope.Logout = function () {
// $http({ url: 'api/UI/Logout', method: 'GET' });
// };
// });
//app.
// controller('mLSController', ['$scope', '$http', 'Logout', function ($scope, $http, Logout) {
// $scope.callLogout = function () {
// Logout();
// };
// }]).
// factory('Logout', ['$http', function (protocol) {
// protocol({ url: 'api/UI/Logout', method: 'GET' }).success(function() {
// $scope.Logout = true; });
// }]);
So my problem is that the current code:
function Logout($http) {
$http({ url: '/api/UI/Logout', method: 'GET' });
}
just isn't called at all, and if I put it on the controller, Logout() is called when the controller is instantiated. Which isn't ideal.
Please help!
If you want the Logout function to be exposed to DOM (via Angular), you need to put it on $scope. There is no other option to call it using angular directives (ng-click).
Else, if you want it to be called before your app/controller are instantiated, use native javascript's onclick() event.
Warning: if you use onclick, you cannot set $scope variables.
So, thanks to Bharat, I've got it working!
This is the solution:
var app = angular.module('mLS');
app.controller('mLSController',
// function added to the controller
function ($scope, $http, $window, $location) {
$scope.Logout = function () {
$http({ url: 'api/UI/Logout', method: 'GET' });
return ;
};
$http({ url: '/api/UI/GetUsername', method: 'GET' }).success(function (data, status, headers, config) {
$scope.userName = data;
$scope.desiredPath = $location.path();
if (!$scope.userName && $scope.desiredPath != '/Account/Login')
$window.location.href = '/Account/Login';
});
});
For completeness, I could wrap the GetUsername call in a function, but the question is answered.
I can't upvote your answer, Bharat, because I haven't asked enough questions yet, but thanks so much!

Fetching data from local JSON File in angularjs

I want to fetch data from JSON file which is on my local machine. But I am not able to get the data. It is showing some cross domain error for $http.
Here is my code.
angular.module('myApp',[])
.controller('myCtrl', function ($scope, webtest) {
webtest.fetch().then(function (data) {
$scope.accounttype = data;
})
});
.factory('webtest', function($q, $timeout, $http) {
var Webtest = {
fetch: function(callback) {
return $timeout(function() {
return $http.get('webtest.json')
.then(function(response) {
return response.data;
});
}, 30);
}
};
return Webtest;
});
Anyone please help me how to display data from local JSON file?
Thanks in Advance.
It's very simple like
$http.get('phones/phones.json').then(function(response) {
$scope.phones = response.data;
});
Refer:http://stackoverflow.com/questions/21589340/read-local-file-in-angularjs
Don't you have an error message like "$http: is not defined" ?
I tried with a controller, this is working :
var ngApp = angular.module("ngApp", []);
ngApp.controller('myController', ['$http', function($http){
var thisCtrl = this;
this.getData = function () {
this.route = 'webtest.json';
$http.get(thisCtrl.route)
.success(function(data){
console.log(data);
})
.error(function(data){
console.log("Error getting data from " + thisCtrl.route);
});
}
}]);
If you haven't, use web developer tools (Ctrl+Shift+I in firefox).
If you haven't already done so. Try setting up a crossdomain policy for your application.

Ionic reading json file from web

After trying what this question ask, I'm asking again how to retrieve data from web using AngularJS in the Ionic framework.
Basically, I do what the answer says:
.factory('Advices', function($http) {
var advices = null;
$http.get('http://myurl.myext/myfile.json').success(function (data) {
advices = data;
}).error(function(error) {
console.log('error'); //even if there i print the error it prints nothing
});
//etcetera
How can I rescue that file from my server?
Please try to following code
var app = angular.module('myApp', ['ionic']);
app.controller('mainInfoFactory', ['$scope', '$http', function($scope,$http) {
$http.get("http://myurl.myext/myfile.json")
.success(function (response)
{
$scope.advices = response;
})
.error(function(data) {
alert("ERROR");
});
}]);
Here myAPP and mainInfoFactory are AngularJS application name and controller respectively.
For example : ng-app="myApp" ng-controller="mainInfoFactory"

AngularJS : Factory JSON Array with HTTP GET

I'm developing my first AngularJS app using the Google Docs API to pass it JSON data.
This is an example of the factory I'm using:
app.factory('Data', ['$http', 'apiKeys', function($http, apiKeys){
var googleDocs = 'https://spreadsheets.google.com/feeds/list/';
return {
news:function () {
return $http.get(googleDocs + apiKeys.googleDoc +'/1/public/values?alt=json', {cache: true});
},
updates:function () {
return $http.get(googleDocs + apiKeys.googleDoc +'/2/public/values?alt=json', {cache: true});
},
docs:function () {
return $http.get(googleDocs + apiKeys.googleDoc +'/3/public/values?alt=json', {cache: true});
}
}]);
I wanted to clean up a bit the code and decided to use services instead of making the calls in the controller itself. It works normally, but it's a pain in the ass the fact that I still need to write long $scopes because of the structure of the Google API. This is how I get the values in the controller:
app.controller('homeCt', ['$scope', 'Data', function ($scope, Data){
Data.news().success(function (data) {
$scope.totalNews = data.feed.entry.length;
});
}]);
Is there a way that I can set the factory service to pass me the data just using:
$scope.totalNews = Data.news()
Or at least removing the 'feed.entry'?
Data.news().success(function (data) {
$scope.totalNews = data.length;
});
Thank you very much!
example of service - resolve the success with the data you want
app.service('Data', ['$http', 'apiKeys', function($http, apiKeys){
var googleDocs = 'https://spreadsheets.google.com/feeds/list/';
this.news =function(){
return $http.get(googleDocs + apiKeys.googleDoc +'/1/public/values? alt=json', {cache: true})
.then(function(data){
return data.feed.entry.length;
});
}
}]);
the controller - since you already resolved the data in service hence..
app.controller('homeCt', ['$scope', 'Data', function ($scope, Data){
Data.news().then(function (data) {
$scope.totalNews = data;
});
}]);
working example
var app = angular.module('app', ['ionic'])
.service('Data', ['$http',
function($http) {
var googleDocs = 'https://spreadsheets.google.com/feeds/list/1aC1lUSxKatfxMKEy1erKDSAKgijSWOh77FDvKWhpwfg/1/public/values?alt=json';
this.news = function() {
return $http.get(googleDocs, {
cache: true
}).then(function(res) {
return res.data.feed.entry;
});
}
}
])
.controller('homeCt', ['$scope', 'Data',
function($scope, Data) {
Data.news().then(function(data) {
console.log(data);
})
}
]);
I'll give you a way of doing it, a way that I don't recommend at all (a service should not handle the scope), but for me it is the only way you have if you don't want to destroy the "async" of your ajax call :
app.factory('Data', ['$http', 'apiKeys', function($http, apiKeys){
var googleDocs = 'https://spreadsheets.google.com/feeds/list/';
return {
news:news,
updates: updates,
[...]
}
function news(scopeValue) {
$http.get(googleDocs + apiKeys.googleDoc +'/1/public/values?alt=json', {cache: true}).success(function(data){
scopeValue = data;
});
}]);
and then, call it that way in your controller :
Data.news($scope.totalNews);