angular js http post not writing to file - javascript

This is my app
objectsApp.controller('ObjectsController', ['$http', '$scope', '$routeParams',
function($http, $scope, $routeParams) {
$http.post('1object.json', "my first write").then(function(data) {
console.log(data)
})
}]);
When run, this is the response (data)
Object {data: "", status: 200, headers: function, config: Object, statusText: "OK"}
However, there is no change to the file 1object.json (expected my first write)
The file 1object.json exists, but is just blank. I am running on a windows machine.
Why wouldn't this be writing?

If you are using Node.js you can use the fs module to get the functionality you want.
In your server.js you would have a route which your angular $http.post directs to, and that route would use fs.writeFile and the posted data to write the .json file.
EDIT: I would like to mention, depending on what your use for the JSON file is, you may consider using a database like redis to store your JSON data.

Related

How does server pipe() a JSON object to my AngularJS application?

I am building a web application using angularJS with Node.js backend. I am new to them both and after several attempts, I made it work to let Node.js request a JSON (using request module) and sent it to angular. However, I am pretty confused about how it works.
Here is my code,
Node.js:
app.get('/query', function(req, res){
if (!req.query.func) { // query TIME_SERIES_DAILY
var request_url = 'http://API';
var data = request(request_url);
console.log(typeof data); // Object
data.pipe(res);
{
AngularJS:
myControllers.controller('ListController', ['$scope', '$http', function($scope, $http) {
$http.get('http://localhost:3000/query').then(function successCallback(data) {
console.log(typeof data); // Object
}, function errorCallback(data) {
// error msg
});
}]);
After I console.log() the type of data at both ends, they are all "Object". In my understanding, both of them parsed JSON string into JSON object (if I was wrong please correct me). But how did node.js pipe() an object? (In my understanding only stream can be piped)
Can anyone explain it for me? Thanks!

angularjs, ui-router access to parameter at the beginning in the state url

I have a frontend web application written enterely in HTML5/JavaScript and the MVC is managed by AngularJS framework using UI-Router.
Now... I have the need to manage more customer with a single application using this pattern:
all customer have an applicationName (System.String)
the url to access into the application is [domain]/:applicationName/[view state] like: http://domain.com/MyName/login or http://domain.com/MyName/home/dashboard
so into the config function of Angular's bootstraping file I have to do something like this:
.state('home.dashboard', {
url: '/:applicationName/home/dashboard',
templateUrl: '/views/contents/dashboard.html'
});
so the problem is: applicationName is an unique name to retrieve the corrispondent applicationId (System.Guid) stored into the database (this applicationId is used to retrieve the corrispondent applicationName data from the database and so is used into all requests).
so the question: before to resolve the state url can I retrieve the applicationName and do the request to a rest api to get the corrispondent applicationId and store it in an angular service; then go to the state.
is it possible? and if yes, how can I do this?
thanks so much to everyone!
Lorenzo
I think you should use $locationChangeStart event in app run function where you can fetch the application Name from Database (using service/provider).
app.run(["$rootScope", "$location", "$window",function ($rootScope, $location, $window){
$rootScope.$on("$locationChangeStart", function (event, next, current) {
alert($location.$$path);
});
}])
This can be done in many ways. I have a recommendation though,
Have a default route and write a controller
Inside the controller please ensure to call the API and get the application id
Inside the controller you can do the $state.go()
See:
https://github.com/angular-ui/ui-router/wiki/URL-Routing#using-parameters-without-specifying-them-in-state-urls

Sending data (received from backend) from on html to another with angularJS

I feel like tons of people do this all the time, and yet I have been unsuccessful in finding similar examples.
I am getting data from the backend using angularJS ($http.post) to a controller in a javascript file, and presenting it in one html. The data is received after sending a search query from that html. Now, I want to "export" that data to another JS file and to present some of it again, in a new html. The problem is that I have access to that data only through the Search Controller during the searching session, and I probably need to store it somehow or send it to another controller/ JS file.
Unfortunately, I cannot use $cookies. Also, I am trying to avoid sending a new request through the server if I don't have to.
I have read a some about services in angular, however, I am new to angular (and UI in general), and for some reason was unable to implement this for my specific case.
Here is an example of the relevant controller, after getting a search request from the html page:
app.controller('SearchCtrl', ['$scope', '$http',
function($scope, $http) {
$scope.searchJSON = {
searchToken: [],
searchOption: []
$scope.sendSearch = function() {
//preparing JSON to send request to server
$scope.searchJSON["searchToken"] = this.search.searchToken;
$scope.searchJSON["searchOption"] = this.search.searchOption;
var json = $scope.searchJSON;
//sending and getting response (JSON object)
$http.post("http://some_host", json)
.success(function(response) {
$scope.collections = response.searchResults;
});
};
}]);
So the data I am interested in passing on to another JS file is in $scope.collections , which is a JSON file (I don't want use the same JS file for both html pages, so was hoping to call that data from a new controller in a new JS file).
Will appreciate any answers, leads, or similar examples from the web. Thank folks!
One possible way to solve this is by using sessionStorage/localStorage on $window. You can store your data there and after redirecting to another file, you can use it by invoking.
You are right to bring up services because that is how I would personally implement this. Create a service to handle the search request and also to store the result via promises:
angular.module('yourModule')
.factory('searchService', function($http, $q) {
var searchService = {
resultsPromise: null,
sendSearch: function(token, option) {
var dfd = $q.defer();
var json = {
searchToken: token,
searchOption: option
};
$http.post("http://some_host", json).then(
function(response) {
// resolve your deferred
dfd.resolve(response.data);
},
dfd.reject
);
this.resultsPromise = dfd.promise;
return dfd.promise;
}
};
return searchService;
});
Then in your current controller, just do:
app.controller('SearchCtrl', ['$scope', 'searchService',
function($scope, searchService) {
$scope.searchJSON = {
searchToken: [],
searchOption: []
$scope.sendSearch = function() {
searchService.sendSearch($scope.searchJSON.searchToken, $scope.searchJSON.searchOption);
};
Then in your other file, simply look at the currentResults of the same service:
app.controller('OtherCtrl', function($scope, searchService) {
if (searchService.resultsPromise) {
searchService.resultsPromise.then(function(results) {
$scope.results = results;
});
}
});
You can ditch the $http service and use $resource instead. From there you can use $cacheFactory as seen in this post: How to cache an http get service in angularjs
An alternative solution is http://jmdobry.github.io/angular-cache/ which works well with ngResource and can also easily be configured to sync to localStorage, so requests don't need to be re-done after page refresh.
`$resource('my/kewl/url/:key', { key: '#key' }, {
'get': { method: 'GET',
cache: $angularCacheFactory('MyKewlResourceCache', {
storageMode: 'localStorage' })
}
});`

How can I access value in json in AngularJS

I am using nodeJS so the server will send the following json object to controller by doing:
data = {
"question": "theQuestion",
"answer": "theAnswer"
};
res.json(data);
Then in the controller, I want to manipulate the variable like:
data = QA.get();
$scope.q = data[question] + "Some additional info here";
QA is the service defined as:
angular.module('questionServices', ['ngResource'])
.factory('QA', function ($resource) {
return $resource('/qa');
});
However, the error message always tells me that data[question] is undefined. What is the right way to access the value? I have tried data.question. It doesn't work either.
I know I can simply show the json values by using ng-repeat in html but I want to be more flexible managing the values.
Seems you QA function you use $http or $resource to get the ajax response.
If you return $http.get/$http.post in you QA service, you can use this code to handle the json response:
QA.get().success(function(data){
console.log(data);
console.log(data.answer);
}).error(functoin(data){
//handle error here.
});
If you use $resource in your QA service, then you can use this code to handle that:
QA.get().$promise.then(function(data){
console.log(data);
console.log(data.answer);
}).then(function(error){
//handler error here.
});
Here is $http document.
Here is $resource document.
P.S you need to understand in ajax, javascript handle the request in async. That means when
exec these code:
$scope.data = QA.get()
console.log($scope.data); // QA.get() send a http request. Now data is still promise object.
you cannot get this response immediately. So if you try to log the data, or use console.log(data.answer) to get data.answer. you will get undefined
However in you html view. You can get the data with {{data|json}} . This is because angular will $watch your data. And once data($resource promise object) is change(means http request is finished), Angular will render your view automatically.
That's why in your view you can get data.answer. But in your controller, you cannot.
$scope.data = QA.get();
console.log(data);
or in your template: {{data | json}}
This will give you a hint

Use require() outside Node.js

I'm experimenting to get an Angular.js application working with Node.js.
Currently I have the code below in the file MY-PROJECT/public/js/controllers.js
function LoginController( $scope )
{
// fetch waiters
var Waiter = require( '../models/waiter.js' );
}
LoginController.$inject = ['$scope'];
As you can see, I'm using require() to access a model file. But it seems like the require()-function is not accessible in this file / folder.
The error I get in the console when I visit the page is:
ReferenceError: require is not defined
The reason for the error is most certainly because I directly include this controllers.js-file in my HTML-file with script-tags (so the require()-function from Node.js is not available).
Now my question is: how can I access a model-file (eg. from MY-PROJECT/models/waiter.js) in the controllers.js-file?
Many thanks in advance!
RequireJS looks like it has what you need.
I was doing it all wrong. Because I'm making a 'realtime-app' (is that the correct name?) and using Socket.io, it works differently.
In the client-controller, I send a message to the server to request the data. The server fetches the data and send it back to the client.
So in the client I actually don't need to require the model, because I get the data in JSON-format from the server.
This is how I solved it, may be useful to others:
/**
* Login controller
*/
function LoginController( $scope, socket )
{
// listen to server when it sends you the cats
socket.on( 'here-are-all-the-cats', function ( cats )
{
$scope.cats = cats;
});
// send message to the server, to request the waiters
socket.emit( 'i-want-all-the-cats' );
}
WaiterController.$inject = [ '$scope', 'socket' ];
Note: I used 'cats' instead of 'waiters', just to make it more clear to others.

Categories

Resources