Explain the service.js in AngularJS - node.js

I'm quite new to AngularJS and NodeJS. I'm trying to develop an app using MEAN stack. I just looked through the sample code in the mean.io boilerplate. I created my own app referring the sample app. I'm trying to submit the AngularJS front end and expecting it to call NodeJs server side but it isn't working. I think service.js is messing up something. Here is the service code of sample app. Can any one explain what this code does with respect to Angular client side and NodeJS Server side.
'use strict';
//Articles service used for articles REST endpoint
angular.module('mean.articles').factory('Articles', ['$resource', function($resource) {
return $resource('articles/:articleId', {
articleId: '#_id'
}, {
update: {
method: 'PUT'
}
});
}]);

It creates a new factory in angular called Articles. The Articles factory has the $resource service injected. The $resource object is used to setup an object for communicating with a RESTful service, in this case "articles/:articleId" the articleId will be pulled from the _id of the resource objects that are returned from queries using this $resource. When you call to update on one of the resources it will use the PUT HTTP Verb.
By itself this just defines the factory but doesn't actually make any calls you would need to inject this and use it somewhere like Articles.query();
From the docs
If the parameter value is prefixed with # then the value of that
parameter is extracted from the data object (useful for non-GET
operations).

Related

Firebase for MVC based projects

I'm struggling with Firebase due to it's asynchronous behavior. Let me explain what problem I'm facing
As you know in MVC we do logic in our Controller, and then pass the output or data to the VIEW. But using Firebase we can't pass data to the view because Controller will not wait for Firebase response and will initialize the VIEW.
class Controller{
index(){
var data = getDataFromFirebase(); // controller will not wait for this
return view('users', data);
}
}
So how we can handle this situation? How to get the data from the Firebase and then pass to the View in Controller.
I have test it in Laravel, Adonisjs -NodeJS Framework, Spring Boot MVC
But not works in any framework to check may be there could be a solution for this problem but didn't found any one. You can suggest the solution in any framework or language as I mentioned.

Passing Data from Node-Express backend to Vue component

I'm still learning Vue.js 2 so I do apologize if this question is a bit silly. I'm building an application using MongoDB, Node, Express and Vue. Normally I'd use a template engine such as Ejs where data passed through Express's res.render method can be readily captured in the template.
Is there a similar way to pass data from backend to the root Vue component? For example, normally, a get request fetches some data from Mongodb, express will render the template file and pass data to it.
app.get("/gallery/:id", function(res, req) {
var id = req.params.id;
database.findById(id, function(err, data) {
....
res.render("home", data);
}
});
Now my root Vue application is attached to html file. I'd like to be able to dynamically render the app with data returned from the database.
I've built an app before that streams data from an api and passed it to my Vue component via socket but I feel like using a socket in this case is unnecessary.
Use http. What's the problem? You can use XmlHttp, or a lot of folk seem to be using Axios. Trigger the call in the onload of your page, or use one of the vue lifecycle hooks. The very good vue docs don't have much to say about how and when to do this. We do it in the onload of the page, and we instantiate vue when the request for page data returns.
The question has already been answered, but I wanted to share my approach. I've been experimenting with rendering an object server side using res.render(), putting it in a div where display: none, and then grabbing the object on the client and passing it to Vue's data attribute.

React Node API Request Design Pattern

I need to make an API request to an external API using an API Key. I know how to make this API request in React by writing a onSubmit function. But since I have an API key that I want to keep a secret I am going to write a simple Node app to house env variables.
Besides messing around in node this is my first production experience with Node and I am wondering if my thought process is correct and if not, the better way to do this.
Most of this question will be pseudo code since I haven't started with the Node portion yet.
The idea is that from within the React component it would call the Node app who in turn would call the external API.
React -> Node -> External API
So the React component would be something like so:
handleSubmit: function() {
var data = this.refs.testData.getDomNode().value;
$.ajax({
url: '/my-node-endpoint',
dataType: 'json',
type: 'POST',
data: { test: data },
success: function(data) {
// Whatever success call I want to make
}.bind(this)
})
}
And then in my Node app it would like something like this:
app.post('/my-node-endpoint', function(req, res) {
// Store the values we are posting as JSON
// Start the post request
// On End tell the React component everything is ok
// Prosper
});
As always, thanks for any help that is offered.
Your thought process looks right to me.
If the API you are calling is from a different domain, you will have to build a wrapper on your node server like you did here. Unless the external API supports cross-origin requests with no domain restrictions (such as MapBox web services), you will have to do this.
Several improvements to your code:
As far as I know, you can use React.findDOMNode(this.refs.testData).value instead of this.refs.testData.getDomNode().value. getDomNode() is deprecated in v0.13.
For all the AJAX calls, you can use the Store concept in Flux. The store keeps the states of the data, including updating data through AJAX request. In your React UI code, you just need to call the methods of the store, which makes your UI code clean. I usually create a store class myself without using Flux.

Building a simple RESTful API with Mongo and Node

So I'm working with a project that recently switched over to Node from Rails, where one of my favorite features was how easy it was to create a simple REST API, like so:
localhost:3000/materials/ Gets a JSON document of all objects
inside materials
localhost:3000/materials/:id Gets a JSON output of the object with
that id, e.g. /materials/123123 gives me item 123123
localhost:3000/materials/ Gets a JSON document of all objects
inside materials
And so on. I'm using Mongo. Is there a way of doing this in Node, or is there a guide or a package I should install that can do this?
Check out LoopBack from StrongLoop Suite, it has a built-in RESTful api explorer that interacts with Mongo using the mongodb connector. http://docs.strongloop.com/loopback/#using-the-api-explorer and http://strongloop.com/strongloop-suite/loopback/
For example, you could create the "materials" model with just the following commands:
slc lb model materials and then the restful api will get auto-generated for you at localhost:3000/explorer.
You can use Restify, to build RESTful Web Services in Node.js
A good tutorial at: https://www.openshift.com/blogs/day-27-restify-build-correct-rest-web-services-in-nodejs
Express seems like what you want. You can specify routes very simply as follows:
app.get('/:collection', function(request, response) {
// the value of :collection is stored in request.params
var coll = request.params.collection;
var search = request.query; // a hash containing the querystring arguments
// do stuff with request body, query parameters, etc.
response.send(data); // send the response
});
app.get('/:collection/:item', function(request, response) {
var coll = request.params.collection;
var item = request.params.item;
// do stuff
res.json(data); // can also send a JSON response
});
Take a look at restgoose. It is a Typescript library that makes simple REST API development super simple.
https://xurei.github.io/restgoose/

Angular Frontend with JAX-RS backend

I have a RESTful Java backend which I made using Jersey, a JAX-RS implementation. This backend is running on a glassfish server on port 8084. I've also made some HTML5/JS/AJAX pages which display the data so I know my REST implementation is working.
I'm trying to develop an HTML5 / JS frontend for this application using the Angular.js framework but I'm experiencing some trouble. I have managed to develop some small webapps in angular which I'm running on Microsoft's IIS on port 80.
Unfortunately, there appears to be a problem with the communication between the two applications. Since I'm new to Angular, I'm unsure if I made a mistake in my frontend code, or if I'm experiencing CORS problems. I already tried running the backend on a Tomcat 7 with the CORS filter but that didn't solve anything.
My angular code looks like this:
services.js
var serviceModule = angular.module('ServiceModule', ['ngResource']);
serviceModule.factory('NodeService', function($resource) {
var NodeService = $resource('http://localhost:port/HtmlJerseyJava/service/node/get/3',{},
{
'get' : { method: 'GET',params:{port:':8084'}}
}
)
return NodeService;
});
controllers.js
function NodeDetailCtrl($scope, NodeService){
var node3 = NodeService.get();
$scope.data = JSON.stringify(node3) ;
}
I hardcoded the ID 3 for now, because I also need to figure out how I can pass the value of an input field from the view to the controller and then to the service. Eventually, the 3 in the service url would be replaced by a variable :nodeId
Any help would be greatly appreciated.
Try the following simplified code:
app.js (for test purposes I suggest you to put functions in one js file)
var serviceModule = angular.module('ServiceModule', ['ngResource']);
serviceModule.factory('Node', function($resource) {
return $resource('http://localhost:port/HtmlJerseyJava/service/node/get/3',{port:':8084'},
{
get {method:'GET'}
});
});
serviceModule.controller('NodeDetailCtrl', function($scope, Node){
$scope.data = Node.get();
}
It would be interesting to now what JSON data your client gets from the REST call.
Greets Marc
I found the solution. There were several steps to fix this problem:
Add a CORS filter to the Jersey servlet on Glassfish.
Upgrade the Angular version to 1.1.x (currently still unstable)
Set a custom header in your resource.
Enjoy a working application.
Big thanks Marcbaur for helping me out here.

Resources