How to inject angular app with api url - angularjs

I am building an angular app that uses a node api. I need a way to bootstrap the angular code with the url of the node api. I would like the node server to have a config file that holds its own url, which may vary based on dev, test, production, etc (e.g. http://localhost:4000/api or http://www.myproductionbox.com/api/v2).
What is the best way to get this the url from the server config file and merge it into the angular source code dynamically?
I am using jade for html templates and I can get something to work using those:
constants.jade:
|angular.module('myApp', []).value('baseUrl', '#{apiBaseUrl}')
where apiBaseUrl is defined in a config file. The express app renders the jade file like this:
app.get('/constants', function(req, res) {
res.render('constants.jade', { apiBaseUrl: settings.api.baseUrl })
})
This works but feels hacky. What's a better way?

We use an inline <script> to hold all those type of config parameters. Such as
<script>
window.config = {
baseUrl: '#{apiBaseUrl}'
};
</script>
This way your angular app can still live in an external file served from a cdn or something.
And then in your app you do what you were doing before with a slight modification.
angular.module('myApp', []).value('baseUrl', window.config.baseUrl)
You could also create a ConfigService in your app that exposes window.config. Then its easier to mock out those values in your tests.

Related

Sending all routes or paths to angular

In my node js app.js I want that whatever the url is it goes to my angular/html page i.e. begin.html, app.js resides in server folder and begin.html is in client folder of my project. It's like :-
-Project
----Server
---------app.js
----Client
---------begin.html
What should I type in app.js so that all the urls go to begin.html where i am using Angular routing?? I think its something like..
var begin=require('../Client/begin.html);
app.use('*',begin);
If you are going to just have all routes go back to that HTML page, then you could just use a web server like Nginx serve that directory statically.
It looks like you are using Express, but that is just a guess. If you want to make HTTP requests from your Angular side to your Node.js side then you will probably want the default response to return your HTML, but still be able to allow requests through. I would look at using the static method from express to expose a static directory while still allowing you to build other routes (i.e. api routes).
It might look something like this:
// Already created express app above
/*
This will default to using index.html from
your Client directory and serve any other resources
in that directory.
*/
app.use(express.static('../Client'));
// Any other routes
app.listen(3000); // Or whatever your port is
Or you could also implement it using the 404 error handler style and return your default file:
/*
This comes after all of your other
route and middleware declarations and
before the .listen() call
*/
app.use(function(req, res, next) {
res.sendFile(path.join(__dirname + '/../begin.html'));
});

How to send an AngularJS file with ExpressJS?

I'm new with ExpressJS, I have a small example using EJS, but I want use AngularJS for manipulating the DOM. Both technologies offer me DOM manipulation, so why some people use it together? I don't understand.
I have no idea how to render HTML files. What is the correct way to use AngularJS with ExpressJS?
res.render('index.html');
As far as I know EJS is really for templating, none of the embedded js is executed on the client.
Personally I have found some cases where it is handy to use a templating language with AngularJS or any client side framework. For example, sometimes it is nice to be able to interpolate some csurf tokens, or session data required by the client app into your html on the server. Other times it is not necessary.
As for rendering html, use the express.static middleware. It comes with Express, you pass a file path, and it returns a handler that will serve the contents of a given directory. You could put express.static anywhere in your middleware chain, but I usually put it at the top to avoid naming issues. Read the documentation for more information.
Consider the following:
var express = require('express')
var app = express();
// Asssuming we have a directory
// `public` in the root of the application
app.use('/', express.static(__dirname + '/public'));
// now you're serving all the files in public directory off the root path
// Add middlewares and routes...
For a really simple app you could you use the fs module, and stream the contents of a file to the response. The following is naive example of how you could do this, in production you would want to listen for error events and implement some cache control.
app.get('/', function(req, res) {
res.set('Content-Type', 'text/html');
fs.createReadStream('./index.html').pipe(res);
});
Please use this :to render first time
and for more information please go her http://www.tutorialspoint.com/nodejs/nodejs_express_framework.htm
var express = require('express');
var app = express();
app.get('/', function (req, res) {
res.sendFile( __dirname + "/" + "index.html" );
})

How to integrate AngularJS with Expressjs & NodeJS ? How to replace Jade with angular?

I have jade as default templates and want to remove completely and use angular instead. How to do it ? How to remove Jade from the package ?
I want to use Plain HTML + Angular for creating frontend without ejs or any package.
Place this in your express app.js file or edit it if already present:
app.use('/', express.static(path.join(__dirname, '/your directory')));
remove any other lines like app.set(views... or app.set(view engine).
First, you need to set your view engine in your Express main app.js file to html.
app.set('view engine', 'html');
Remove all the configurations made in your app.js using
app.set
Now, we need to remove the Jade template engine module from our list of packages installed
npm uninstall jade
Now update your package.json file with
npm update -g
We have now set up our template engine as HTML and now we need to update our express app.js to point to directory for Angular js
Default we use Public directory
app.use(express.static(path.join(__dirname, 'public')));
Now place your Angular js code in public directory of your Express app.
Also, make sure to change the routes accordingly in Angular which will point to Express Node js routes defined as required by your app.
You don't need to use jade with angular.
You can still make html templates with angular in stead.
The way to do that is to create a tag in your html
like:
<your-tagname> </your-tagname>
then you create a simple directive inside your angular js code.
pl.directive('yourTagname', function(){
return {
restrict: 'E' ,
templateUrl: 'view/yourhtmlpagename.html'
};
});
This will load any html sniper/content inside your custum html tag.
If you don't create any jade files, that will be easily ignored.
Only make sure to point to your index.html and not index.jade in your express code if you use node.js.

environment specific config with angularjs

I am working on creating a website with Angularjs and WebAPI as backend support with Visual studio.
I have defined the url to webapi in app.config.js as an app constant:
var serviceBase = 'http://localhost/Webapiservice/';
app.constant('ngAppSettings', {
apiServiceBaseUri: serviceBase,
clientId: 'ngTestApp'
});
Now for QA environments (http://QAServer/Webapiservice/), the webapi resides at a different URL, the same goes for our production environment (http://ProdServer/Webapiservice/).
I can manually update the js file to the appropriate location. But is there a way to automate this process so webAPI is pointing to the correct URL?
Is it possible to do this with grunt? Again I have never used grunt before.
ngConstant does a great job, along with grunt: https://github.com/werk85/grunt-ng-constant. This way you can specify your environments as JSON files and on compile/run time, grunt generates a enviornment.js file with a module (I call mine always ENV), which can be injected in every part of your application.
I would do something like this:
angular
.module('app', [])
.value('$path', {
rest : "http://localhost/Webapiservice"
})
you will call something like this:
app.constant('ngAppSettings', {
apiServiceBaseUri: $path.rest,
clientId: 'ngTestApp'
});

AngularJS and Express Routing issue

I'm using AngularJS and ExpressJS and having an issue with routing. I saw many other posts but none of those solutions seemed to work. Here is my routes in Express:
module.exports = function(app, auth) {
//Api routes
var mycontroller = require('../app/controllers/mycontroller');
app.get('/api/dostuff/:id', mycontroller.getBlockByHash);
//Home route
app.get("/", function(req, res) {
res.render('index');
});
};
When I go to my root /, everything works as expected. ExpressJS serves up my index and angular picks up the rest. When I click a link /blocks, it works as expected since AngularJS picks up the route. But when I refresh, I get a 404 not found error.
I tried app.get('*' instead, but that gives me a completely different error where nothing loads.
I'm using Jade to create the basic page structure with Express. My Express config is:
app.use(express.favicon());
app.use(express.static(config.root + '/public'));
When using html5Mode the documentation says:
Using this mode requires URL rewriting on server side, basically you have to rewrite all your links to entry point of your application (e.g. index.html)
What it doesn't mention is:
You should exclude static assets like scripts/styles/images/fonts etc.
You should also exclude your Restful API.
Your case:
The error you got there is express serving html into script tags and the browser fails to parse them as a valid javascript.
Use express.static to serve static assets and then use app.get('*', for redirecting all other requests to your angular.js entry point (index.html).
express.js middleware order do counts!
express.static must be declared before app.router
Node.js / Express.js - How does app.router work?

Resources