
Node js
JavaScript on the server
Node.js is a JavaScript runtime built on Chrome's V8 JavaScript engine.
Allows us to run JavaScript on the server
Primarily Designed "to build scalable network applications"
- http
- file system
- comand line/console
Development Diagram


Node Application Structure
Just a script file
index.js
// Call the console.log function.
console.log("Hello World");
Node Server
// Load the http module to create an http server.
var http = require('http');
// Configure our HTTP server to respond with Hello World to all requests.
var server = http.createServer(function (request, response) {
response.writeHead(200, {"Content-Type": "text/plain"});
response.end("Hello World\n");
});
// Listen on port 8000, IP defaults to 127.0.0.1
server.listen(8000);
// Put a friendly message on the terminal
console.log("Server running at http://127.0.0.1:8000/");
Node Application
Module Loading
const PI = Math.PI;
exports.area = (r) => PI * r * r;
exports.circumference = (r) => 2 * PI * r;
const circle = require('./circle.js');
var area = circle.area(4);
console.log(`Area of circle of radius 4 is ' + area);
index.js
circle.js
Lab

NPM
Package Manager for JavaScript
- download our dependencies using NPM.
- comes bundled with Node
- package.json - describes our app and it's dependencies
{
"name": "module-name",
"version": "1.0.0",
"devDependencies": {
"jasmine": "*"
"lodash": "3.9.3”
},
"dependencies":{}
}
npm install
npm install lodash --save
Unit Testing

Jasmine
- Behavior-driven development framework for testing JavaScript code. It does not depend on any other JavaScript frameworks.
- Does not require a DOM
- Simple syntax makes it easy to read and write tests
Basic Jasmine Test Suite
describe("A suite", function() {
it("has a spec with an expectation", function() {
expect(true).toBe(true);
});
});
Suites
- suites created with describe function
-
takes two parameters:
- string :name or title for a suite
- function: block of code that implements the suite
describe("A suite", function() {
//it("has a spec with an expectation",
//function() {
// expect(true).toBe(true);
// });
});
Specs
- specs created with jasmine it function
-
takes two parameters:
- string :name or title for a spec
- function: the spec/test itself
- contains one or more expectations
//describe("A suite", function() {
it("has a spec with an expectation",
function() {
// expect(true).toBe(true);
});
//});
Expectations
- assertion that is either true or false
-
compares expected value with actual value using matchers:
- toBe
- toEqual
- toBeNull
- toContain
//describe("A suite", function() {
//it("has a spec with an expectation",
//function() {
//expectation passes
expect(true).toBe(true);
//expectation fails
expect(false).toBe(true);
//});
//});
Spies
- Jasmine's version of test doubles/mocks
- spy stubs a function and tracks calls to it
-
have special matchers like
- toHaveBeenCalled
- toHaveBeenCalledWith

Test Runner
- Automates your test runs
- Can run tests in multiple browsers
- Watches files and automatically reruns tests
lodash
A modern JavaScript utility library delivering modularity, performance, & extras.
lodash is a utilty library that helps with
- Iterating arrays, objects, & strings
- Manipulating & testing values
- Creating composite functions
Lab

Angular 1.5
What is Angular?
Framework for building dynamic web apps
- Data Binding
- Dependency Injection
- Routing (single page application)
- Filters and Directives
We need to build client-side apps to consume our back-end services


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Sample HTML Page</title>
</head>
<body>
This is a sample HTML page
</body>
</html>
Static HTML
Rendered Page
We want to build apps that can do more on the client-side
- More fluid user experience
- No page loads (Page will never reload inside of application)
- Provide quicker feedback to users
- Client side does processing (using less of server’s resources)
Data Binding


There are a lot of frameworks that do similar things
Modules
Container for different parts of your apps
-
components
-
services
-
filters etc.
<html>
<body>
<div ng-app="myApp"></div>
</body>
</html
var app = angular.module('myApp', [/*list of app's dependencies*/]);
//app variable is an instance of our module
//the Module api has methods we can use to create services, components etc.
app.service("myService", function(){
//service code here
});
app.component("myComponent", function() {
//component code here
});
//best practice though is to get reference to module as shown below
angular.module("myApp").service("someService", function(){});
app.js
index.html
Recommended Use for Modules
- A module for each feature
- A module for each reusable component (especially directives and filters)
- And an application level module which depends on the above modules and contains any initialization code.
Lab
Components
Motivation
webcomponents
What Are Components?
Web Components
Spec gives us a way to create custom html elements

Web Site Is Tree of Components

//todo-app contents
<create-todo></create-todo>
<todo-list></todo-list>
<todo-filter></todo-filter>
...but still not fully supported in browsers
Angular Components
Allows Us To Create Apps In Way Similar To Using Web Components
<body ng-app>
<menu></menu>
<user-info></user-info>
<message></message>
</body>
Component Combines
- Template
- Controller
- Bindings
Registering Component With Module
Use the .component() method which takes two arguments
- Name of the component (as string)
- Component config object
angular.module('module')
.component('myModule', {});
Component Syntax
var myComponent = {
templateUrl: "my-template.html",
template: "<div></div>"
controller: MyController,
bindings: {
title: '<',
description : '&'
}
}
function MyController(){
}
angular.module("myModule").component("myComponent", myComponent);
One Component Per File
Naming
javascript: "my-component.component.js"
html: "my-component.component.html"
Template
var myComponent = {
templateUrl: "my-template.html",
template: "<div></div>"
//controller: MyController,
//bindings: {
// title: '<',
// description : '&'
//}
}
//function MyController(){
//}
angular.module("myModule").component("myComponent", myComponent);
Template
This is the view for the controller
//component.html
<div>
<p>
{{$ctrl.text}}
</p>
</div>
Unless the template is very small, we will want to move template into it's own file and use templateUrl property
//component.js
var myComponent = {
templateUrl: "component.html"
}
Controller
var myComponent = {
//templateUrl: "my-template.html",
//template: "<div></div>"
controller: MyController,
//bindings: {
// title: '<',
// description : '&'
//}
}
function MyController(){
}
angular.module("myModule").component("myComponent", myComponent);
Controllers Are Used To
- Set up initial state of the component
- Add behavior to the component
Angular Calls "new" on Controller instance
Angular then makes the return value from calling "new Controller()" available to the view (our template) via a variable named "$ctrl"
- $onInit()
- $onChanges()
- $onDestroy()
- $postLink()
Best practice is to put any initialization code for component in the $onInit function
Component Lifecycle
Components can implement "lifecycle hooks"
These are methods that will be called at certain points in the life of the component
Lab
Bindings
var myComponent = {
//templateUrl: "my-template.html",
//template: "<div></div>"
//controller: MyController,
bindings: {
title: '<',
description : '&'
}
}
//function MyController(){
//}
angular.module("myModule").component("myComponent", myComponent);
Bindings Are A Component's API
-
Inputs: '<' and '@'
-
Outputs: '&'
Components Should Only Modify Their Own Data
Components use '&' binding as outputs
These outputs can be things like callbacks or "Output Events"
var myComponent = {
bindings: {
onUpdate: '&',
onDelete: '&'
}
}
Directives
Directives are markers on a DOM element that tell Angular to attach a specified behavior to that DOM element
Directives can have the following types:
- element names
- attributes
- class names
- comments.
<my-dir></my-dir>
<span my-dir="exp"></span>
<!-- directive: my-dir exp -->
<span class="my-dir: exp;"></span>
Angular has a lot of built in directives
- ng-app
- ng-repeat
- ng-if
- ng-model
- ng-click
Lab
Filters
Filters
A filter formats the value of an expression for display to the user.
{{expression | filter }}
//filters can take arguments
{{expression | filter : arg1 : arg2 }}
They are invoked with the pipe ('|') character
Built In Filters
- currency
- date
- number
- filter (used to select subset of items)
- orderBy
Lab
Services
Purpose of Services
-
Controllers are instantiated when needed and discarded when they are not. Services give us a means for us to keep data around for lifetime of the app and to share data and logic across components.
-
Services provide interface for grouping related methods and allow us to share these methods across controllers.
-
Services are singleton objects and are lazily instantiated, meaning they are only loaded when a piece of our application depends on it.
Methods For Creating Services
-
service()
-
factory()
-
constant(key, value)
-
value(key, value)
- difference between value and constant is constant can be injected into config function
- values can also register objects and functions while constants can not
var app = angular.module('myApp', []);
app.service('myService', function(){});
app.factory('myService', function(){});
app.constant('myConstant', "a constant string");
app.value('myValue', "some value");
One Service Per File
File name follows pattern: "my-service.service.js"
Dependency Injection
Dependency Injection
- Allows us to ask for dependencies - Can have them passed in
- Simplifies Testing - Allows us to pass mocked objects in place of real ones

Methods For Declaring Dependencies
- Using the inline array annotation
- Using the $inject property annotation
- Implicitly from the function parameter names (has caveats)
There are also gulp/grunt tasks that will automatically create the $inject property annotation for you
var app = angular.module('myApp');
//inline array annotation
app.service('myService',
['serviceA', function(serviceA){
}]);
//$inject property
function myService (serviceA){
}
myService.$inject = ["serviceA"];
app.service('myService', myService);
//implicit annotation
app.service('myService', function(serviceA){
});
Lab
Services -cont.
Built In Services
- $http
- wraps XMLHttpRequest object
- $location
- wraps accessing and updating the url in the browser
- $q
- promise service
- $document
- wrapper for browsers window.document object
- $log
- assists in logging errors, warnings etc.
Angular provides built-in services
- $http
- $window
- $location
$http
Angular provides $http service which wraps the browser’s XMLHttpRequest object. The service is a function that takes in an object that configures an HTTP request
$http({ method: 'GET', url: '/api/sample/data'});
This method returns a promise
Shorthand Methods
$http.get('/api/sample/data');
$http.post('/api/sample/data', data);
$http.put('/api/sample/data', data);
$http.delete('/api/sample/data', data);
- get
- put
- post
- delete
Caching
$http allows us to set a flag to cache results from requests we've already made
$http.get('/api/sample/data', { cache: true });
Promises
$http returns promise with following methods -
- then(successCallback, errorCallback, notifyCallback)
- catch(errorCallback)
- finally(callback, notifyCallback)

Slack API
Get A Development Token

Postman
"Get" Request to Retrieve Messages
https://slack.com/api/channels.history?token=<token>&channel=<channelId>&count=<numberToGet>
Formatting Slack Messages
Lab
Routing
UI-Router
Routing framework for Angular that allows you to set up states within your application
Not packaged with Angular - has to be added as a dependency
//npm install angular-ui-router
angular.module('myApp', ['ui.router']);
States
- A state corresponds to a “place” in the application, and describes what the app does and looks like at that “place”.
- Use $stateProvider in your app.config to set up the "states" of your app
- States can take parameters which can accessed later via the $routeParams service
$stateProvider
.state('message', {
url: "/message/{id}",
template: '<message></message>'
});
ui-view
Tells UI-Router where to render the app's current state
<div ui-view="viewA"></div>
UI-Sref
Binds a link (<a> tag) to a state. If the state has an associated URL, the directive will automatically generate & update the href attribute
Clicking the link will trigger a state transition
<a ui-sref="home">Home</a>
Lab
Angular 2
TypeScript
Superset of JavaScript
Adds Types
Angular CLI
Node js Day07 Full Stack
By Tarun Sharma
Node js Day07 Full Stack
Slides for day two of JavaScript for Grad Academy 2016
- 1,115