I'm trying to use angular ngResource module to fetch data from json file but I get an error 404 on the console - the URL is being concatenated with code following the call to get function.
Here is the error:
localhost prefix/test_data/data.json/function%20(data)%20%7B%20%20%20%20%20%20%20%20%20%20%20%20console.log(data);%20%20%20%20%20%20%20%20%7D
here is the code I'm using:
the json service -
angular.module('jsonServices',['ngResource']).factory('JsonService',
function ($resource) {
return $resource('/test_data/data.json');
});
the controller using the service:
angular.module('myApp.controllers')
.controller('mainController', function ($scope, JsonService) {
JsonService.get(function (data) {
console.log(data);
});
});
the app js that starts it all:
angular.module('myApp',['myApp.controllers','jsonServices','ui.router'])
.config(function($stateProvider, $urlRouterProvider){
$stateProvider.state('home',{
url:'/home',
template:'some template path goes here',
controller:'mainController'
};
});
As you can see the "function(data)" is being added to the url as a string. one more thing is when I try to access the json file browsing to its location I can see the content of the json file OK.
Does anyone got this problem before and find a way to solve it? Is there something I'm doing wrong or missing here?
Thanks,
Eran
Found the problem, it seems that I used a bower package call ng-resource instead of angular-resource.
Related
I'm very new to AngularJS and Electron, and i'm currently working on a simple desktop app that reads data from a JSON file and allows the user also update and delete data. I'm also using TaffyDB to query the data. I'm able get data from the JSON file but unable to store it in the JSON file.
What i tried so far was this:
myApp.controller('homeController', ['$scope', '$http', function($scope, $http) {
$scope.saveData = function()
{
var data = $scope.data;
$http.post('/src/db/db.json', data).then(function (response) {
console.log(response);
}, function (response) {
console.log(response);
});
};
}]);
Executing the event on the browser i get the following error:
POST http://127.0.0.1:64262/src/db/db.json 404 (Not Found)
This is normal because we cannot access the user's filesystem from javascript.
When i execute the app as a Electron package, i get the following:
Object {data: Array[2], status: 200, config: Object, statusText: "OK"}
But the file was not modified.
I would like to know if there is any way i can accomplish this using AngularJS and Electron.
Important Note: This app needs to run as a standalone desktop application. In other words, my client doesn't what to install other software or apps to be able to use this application.
You can't write to the file system using HTTP, that's for the web only.
Electron is built on Node.js. So take a look at the Node.js File System module. For example:
fs.writeFile('/src/db/db.json', data, (err) => {
if (err) throw err;
console.log('It\'s saved!');
});
I have to load a JSON file from another server (where I don't have control). After some hours researching found that JSONP is the dirty hack that answers mine pleads.
I am using nodejs, serving the site on localhost:3000 using gulp.
Loading the JSON from localhost:8000
I was able to get an example working, from an URL I do not need (found it randomly on the Internet), using the same code that I had not working with my URL.
That makes me wonder if I am trying to read the file like something it is not? As far as I could research it shouldn't be needed to parse a JSON into JSONP. Am I on the right track?
Underneath, the code which I was talking about:
(function () {
'use strict';
angular
.module('qwe.asd')
.controller('UsersController', UsersController);
/** #ngInject */
function UsersController($http, $log, $sce) {
var vm = this;
var trustedUsersAPI = "http://localhost:8000/users?callback=JSON_CALLBACK";
$sce.trustAsResourceUrl(trustedUsersAPI);
$http.jsonp(trustedUsersAPI, {
'callback': 'JSON_CALLBACK'
})
.success(function (data) {
$log.log("request 1 - OK");
$log.log(data);
vm.users = data;
})
.error(function () {
$log.log("request 1 - KO");
});
var url = "http://public-api.wordpress.com/rest/v1/sites/wtmpeachtest.wordpress.com/posts?callback=JSON_CALLBACK";
$sce.trustAsResourceUrl(url);
$http.jsonp(url)
.success(function (data) {
$log.log("request 2 - OK");
$log.log(data);
})
.error(function () {
$log.log("request 2 - KO");
});
}
})();
And the logs generated...
angular.js:13424 request 1 - KO
angular.js:13424 request 2 - OK
angular.js:13424 Object {found: 12, posts: Array[12]}
And finally, the JSON files I am (mis)reading:
The one I need but I can't have
[{"id":0,"firstname":"front","lastname":"end","email":"frontend#example.com"},{"id":1,"firstname":"back","lastname":"end","email":"backend#example.com"},{"id":2,"firstname":"john","lastname":"doe","email":"johndoe#example.com"},{"id":3,"firstname":"dev","lastname":"eloper","email":"developer#example.com"},{"id":4,"firstname":"ad","lastname":"min","email":"admin#example.com"}]
And the one I don't need but works fine
{"found":12,"posts":[{"ID":XX,"site_ID":XXXX,"author":XXXX(..POSTS DATA WITH NO VALUE HERE..)}]}
P.S. I am really green here, I am on angular since this morning!
For those who come after me, I was following the wrong track. Thanks to the commenters I learnt that JSONP has to be supported on the server (just like CORS does).
Sorry, I'm a newbie at this
Let's say i have the following in node express
router.get('/:name', function(req, res, next) {
res.render("test", {test:req.test});
});
how to do I get the angular to pick up the test variable?
i tried doing in the html page
<div ng-controller='UserCtrl'>{{ data }}</div>
<script>
var test=!{JSON.stringify(test)};
</script>
then on the angular page
productApp.controller('UserCtrl',function UserCtrl($scope){
$scope.data=test;
});
the req.test looks like this
[
{
name: 'test'
}
]
the 'data' shows empty everytime.
thank you for your help
If you want Angular to talk to a server, the most common way is through an AJAX request. Angular has a whole service to help you with this communication.
https://docs.angularjs.org/api/ng/service/$http
The first example pretty much does exactly what you are looking for:
$http({
method: 'GET',
url: '/testName'
}).then(function successCallback(response) {
// this callback will be called asynchronously
// when the response is available
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
It uses promises for the response. Just add your actions in the proper call back function and away you go.
You will need to use ajax call from an angular script or service in order to get the express js backend response.
You can create a service like below -
productApp.service("API", function($http){
this.callAPI = function(name){
return $http({
url : "localhost:3000/"+name,
data : "", // pass data if any here
method: "get"
});
};
});
Then you will need inject this service in your controller and call like below -
productApp.controller('UserCtrl',function UserCtrl($scope, API){
//$scope.data=test;
// call service api here
API.callAPI("some name").then(function(response){
$scope.data = response;
}, function(){
// error goes here
});
});
Also, you can change your express js app to send the JSON data as follows -
res.json({...}); // instead of res.render(..);
Inside your express res.json() is, in my opinion, the best option you have since any object passed to it will be converted to JSON other way you can do it like you've done but render is more suited to html where you have to render a nice little view for the client or there is some sort of manipulation involved before sending the JSON on the wire or the json is too big and you don't want to make you router file dirty and rather delegate that to a view file.. else res.json() is a very neat way to do it.
Modify your controller code like:
productApp.controller('UserCtrl',['$scope', '$http' , function($scope, $http){
$http.get('/test').then(
function(response){
$scope.data = test;
},
function(err){
console.error(err);
}); //'/test' <- this is the url;
//$scope.data=test;
}]);
and remove this from your code
<script>
var test=!{JSON.stringify(test)};
</script>
I would recommend doing an $http service call to receive this variable BUT if you truly want this variable/data rendered directly in to the page and available in the controller, you should consider doing the following:
In the rendered/returned HTML:
<head>
...
<script>
angular.module('myAppConfig', [])
.value('MyTestConfig', !{JSON.stringify(test)});
</script>
</head>
<body ng-app="myApp">
...
<div ng-controller='UserCtrl'>{{ data }}</div>
...
</body>
This will setup an injectable configuration value called 'MyTestConfig'. Ideally, this should be part of a bigger object or service so you could do things like Config.apiPath or Config.getStaticResource('my-resource.png')
Your controller will now look like this:
productApp.controller('UserCtrl', function UserCtrl($scope, MyTestConfig){
$scope.data = MyTestConfig;
});
and your original modal definition will look something like this:
angular.module('myApp', ['myAppConfig']);
You may need to shuffle around where the script tag is depending on how you have configured your views. This will also only work before injection has been finalized, aka, this will not work for partials.
I am beginning my first angular.js app. I have written code to call a spanish rhyming dictionary A.P.I. In this code I log the JSON response to the console. However there is an error when I run this code. The console doesn't give me the specific error but it concerns my app.js file
Here is the website for the A.P.I-
Rhyme Searcher
Here is the repository with my code: https://github.com/Renniesb/rap_in_a_box
Here is my app.js code:
var rhymeApp = angular.module('rhymeApp', ['ngResource']);
rhymeApp.controller('rhymeView', function ($scope, $resource) {
$scope.rhymeApi =
$resource("http://store.apicultur.com/api/rima/1.0.0/flor/true/0/200/true",
{callBack: "JSON_CALLBACK"}, { get: {method: "JSONP"}});
$scope.rhymeResult = $scope.rhymeApi.get();
console.log($scope.rhymeResult);
});
$resource.get() is asynchronous which means that you need to provide a callback function to process the API response. Try using
$scope.rhymeApi.get({}, function(result) {
console.log(result);
});
I'm developing an application using Laravel and AngularJS. For AngularJS pretty URL , i have set $locationProvider.html5Mode(true) and it's working fine. But suppose my url is http://localhost:8000/demo and if i refresh the page, I'm getting NotFoundHttpException in compiled.php line 7693:
Here is my angular's routes.
function($routeProvider,$locationProvider) {
$locationProvider.html5Mode(true);
$routeProvider.
when('/', {
templateUrl: 'partials/index.html',
controller: 'indexController'
}).
when('/dom',{
templateUrl:'partials/dom.html',
controller:'DomController'
}).
when('/demo',{
templateUrl:'partials/demo.html',
controller:'DemoController'
});
}]);
And here's my laravel's route.
Route::get('/', function(){
return view('index');
});
I'd appreciate a little help.
Thanks!
The problem here is that the web server will pick up http://localhost:8000/demo when you refresh the page, and try to handle the request. It's not aware that you wish to use html5 routing. So it will parse the request, say "oh, I should pass this to public/index.php and be done with it". And then public/index.php will receive it and throw an error since the route doesn't exist in Laravel.
What you need to do is to make a catch all type of route in Laravel, and then let Angular's routing take over. You then render your index view on every single request. There's a great answer here on SO on how you do that in Laravel 5: How do I catch exceptions / missing pages in Laravel 5?
This is pseudo code and will not work, just to show an example:
Route::get('*', function() {
return view('index');
});
So, render the index view on every request and then let Angular handle the routing from there.