Using Angular $http service in node app - angularjs

I'm developing a script in Node.js that needs to send multiple http requests. I'm really familiar with the way Angular's $http service works. I like the use of promises and overall syntax, I know its advantages and disadvantages etc.
Can I in any way use Angular $http service in a Node.js app? I hope this doesn't sound too silly.

For promises like the ones in angular you can use q. Actually angular uses a subset of q.

At the risk of self-promotion, I wrote an NPM module that provides promisified HTTP methods.

There's an NPM project for running AngularJS in node on the server located here: https://www.npmjs.com/package/angularjs-server
That being said, you might want to take a look at Bluebird or just use ES6 promises in Node. Since Angular is a client-side framework it has a lot of things you don't need on the server.

node has built in support for simple http requests from the http module - however if you would like something a bit simpler and easier to manage I would reccoment the Restify client API
var restify = require('restify');
// Creates a JSON client
var client = restify.createJsonClient({
url: 'https://us-east-1.api.joyent.com'
});
client.basicAuth('$login', '$password');
client.get('/my/machines', function(err, req, res, obj) {
assert.ifError(err);
console.log(JSON.stringify(obj, null, 2));
});

Related

Appending some info to each requset in REST API

I have an angular application. From frontend I can set some value. This value is something like config, which can be changed.
It is simple string variable. How to attach this config to each REST request ?
I ask mainly about approach.
Maybe pass it via headers is good idea ?
For angular 1.x, write an Interceptor:
For purposes of global error handling, authentication, or any kind of
synchronous or asynchronous pre-processing of request or
postprocessing of responses, it is desirable to be able to intercept
requests before they are handed to the server and responses before
they are handed over to the application code that initiated these
requests
For angular 2.x / 4.x, RequestOptions should be the key to solve your problem. Set base url for angular 2 http requests
I'm using angular2, my solution is create a Service and inject "Http" dependency, then write two methods "get", "post", these methods add an entry to header before calling "Http", in other component / service, I just inject this Service class, then call its "get" or "post".
Your code should be somewhat like this If your working in angular 1.3 or less
The data should be sent as body data to server
var basecall = Restangular.all('url');
bascall.post($scope.config).then(function(data){
})

Blocking / Initialization service with angular.js

My apps are using many web services on the intranet, and url-s for those depend on the server environment.
My apps are hosted on IIS, which adds an HTTP response header like this: Environment: DEV, so every web app knows in which server environment it is running, and thus which intranet servers it must use to call all the services.
Each of my angular apps uses a service that issues a simple GET against the app's own root just to get any response with the environment name in it, and set configuration accordingly.
Question:
How should an angular app implement such a service that would execute as the very first thing in the application, and make sure that while it is getting that first response, nothing in the app tries to execute an HTTP request against other services, or even try to use any configuration provided by my environment service?
Is there a way to implement such a service in angular that could block every other service / factory in the application till it is done initializing itself?
I have many other services in the app, and none of them really know what to do till my environment service has finished its initialization.
UPDATE
Looking at it from another angle.... is it possible to implement such an interceptor in angular that could do the following?:
execute an HTTP request and block the app's execution till it gets a response
make information from the response available throughout the app as a service/factory/config.
Angular lifecycle could be one solution. Using the angular.config() phase you could peek at the headers of the HTTP service.
Create a factory called 'httpInterceptor'
function httpInterceptors(siteConfig, $q, $injector) {
return {
response: function(data, status, headers) {
siteConfig.setEnvironment(headers['Environment']);
return data;
}
};
)
Then in angular.config()
$httpProvider.interceptors.push('httpInterceptor');
If you truly want to block the other option is to use UI router resolve property to block routes loading until the request has been made https://github.com/angular-ui/ui-router/wiki you can add the resolve method to the root state.
Resolve
You can use resolve to provide your controller with content or data that > is custom to the state. resolve is an optional map of dependencies which > should be injected into the controller.
If any of these dependencies are promises, they will be resolved and converted to a value before the controller is instantiated and the $stateChangeSuccess event is fired.

Get raw request / response from $http call

I am writing an AngularJs app to test an API we developed. The app uses the $http object to make requests to the API. One of the asks is that after the call it's possible to review the raw HTTP (headers and bodies) Request/Response, similarly to what's available in Fiddler via Raw tabs.
Is it something that $http provides out of the box?
If not, it appears that the only challenge is gaining access to the actual request http headers. It's easy to get the response headers and request/response bodies, but not sure how to get the actual request headers.
Thanks.
If you are using $http service to make your API calls, you can use Interceptors to achieve what you want.
Here is what docs tell us about them:
For purposes of global error handling, authentication, or any kind of synchronous or asynchronous pre-processing of request or postprocessing of responses, it is desirable to be able to intercept requests before they are handed to the server and responses before they are handed over to the application code that initiated these requests. The interceptors leverage the promise APIs to fulfill this need for both synchronous and asynchronous pre-processing.
You can find more in depth explanation in the official docs. For example, here.
Also, there are some questions about interceptors on this site. There are some examples of their usage for displaying loading screen in applications: here, here and, probably, somewhere else.
Hope, this helps.
Yes, AngularJs is wrapped around some JQuery or internally JQlite if JQuery is not present and written in Javascript and it provides some pre-defined services. A typical service looks like the following.
AngularJS docs: tutorial step 5
$ Prefix Naming Convention You can create your own services, and in
fact we will do exactly that in step 11. As a naming convention,
Angular's built-in services, Scope methods and a few other Angular
APIs have a $ prefix in front of the name.
The $ prefix is there to namespace Angular-provided services. To
prevent collisions it's best to avoid naming your services and models
anything that begins with a $.
If you inspect a Scope, you may also notice some properties that begin
with $$. These properties are considered private, and should not be
accessed or modified.
angular.module('myApp')
.factory('myService', function ($http, $injector) {
'use strict';
return $http.get('/endpoint')
.then(function () {
return $injector.get('endpoint');
}
.error(function () {
// handle error
}
};
})
Have a look a the image in AngularJS docs which shows a number of services with the $ prefix. Mostly, wrappers over service. It is reserved. More at FAQ.

how get a list from google endpoint with angular $resource?

I am trying to call a list from a google endpoint with $resource, before that I was using http, but with $resource seems more clear.
Is just to fill a combobox.
My service.js looks like:
provinciaServices.factory('Provincia', ['$resource',
function($resource){
return $resource('https://local.appspot.com/_ah/api/provinciaendpoint/v1/:provinciaId', {}, {
query: {method:'GET', params:{provinciaId:'provincia'}}
});
}]);
and in my controler I call the list with the following line:
$scope.provincias = Provincia.query();
The recommended way to interact with an Endpoints API is through the client library for js. Read that link if you're doing angular with endpoints no matter what - it's a great resource.
You can use $http to hit your endpoints API as a REST service, but this requires some careful use of routes and HTTP verbs, and OAuth is a little more difficult, if you feel you might want to do that later.
I'm not really sure what your error with $resource is. Could you update your question perhaps?

Response Interceptor Pattern with AngularJS and BreezeJS

On the matter of building a Request Interceptor, the BreezeJS documentation seems to be replete. However, I've been struggling with the my attempts to build a Response Interceptor while using BreezeJs and AngularJs. Does anyone have a good workable example? Thanks.
Breeze can be configured to use angular's $http and $q, so interceptors you create in angular work for breeze requests:
http://www.breezejs.com/documentation/breeze-angular-service
https://github.com/Breeze/breeze.js.labs/blob/master/breeze.angular.js
And you want to look at the JsonResultsAdapter which is used both by query and save to materialize response data from the server into entities on the client.

Resources