Angular2 Learning Note
Why Angular 2
- Frameworks is for large scale JavaScript applications.
- Angular 2 is easy. Simpler than Angular 1.
- Written in typescript, a superset of JavaScript, which implements many ES6 features.
- Similarity from Angular 1
- Mobile oriented and better performance
##ES6 and TypeScript ES6 transpile to ES5, TypeScript act as a transpiler. Here we talk about ES6 and type script.
ES6 new features:
- Classes
- Arrow Functions
- Template String
- Inheritance
- Constants and Block Scoped Variables
- spread and rest
- Destructuring
- Modules
Classes
class SomeThing{
constructur(){
//
}
someMethods(){
//
}
}
the keyword this
this usually refer to the instance of the class. But there are times that this refer to other things.
1 The basic case Method Invocation: In someObject.someMethod(), this in .someMethod refers to someObject.
2 Function Invocation: In someFunction(), this can refer to different things:
- In “strict” mode,
thiswould be undefined - Otherwise,
thisrefers to the context wheresomeFunction()is called.
Confusing Situation 1:
The following code will give an error. Because log is looking for console which is referred by this.
var log = console.log;
log("something");
This can be solved by using .bind() like: var log = console.log.bind(console);. Other solutions would be Function.call or function.apply.
Confusing Situation 2:
Anonymous functions and functions declared within other functions. In strict mode, the following code will have this to be undefined.
class someClass{
fun(){
//
}
foo(){
bar(function callback(err,data){
this.fun();
});
}
}
In ES6, the feature of arrow function resolves this problem.
Arrow Functions
Basically a new syntax for dealing with this.
A simpler way of defining anonymous functions. revisit anonymous functions
Instead of:
items.forEach(function(x){
//do something with x, and
})
We can do:
items.forEach((x)=>{
//do something with x
})
Can be used with all kinds of call back. Like forEach, map, reduce.
Major Difference Arrow function does not set a local copy of this, arguments, super, new.target.
new.target, this, super in a arrow function is scoped from the outer enclosure, there is no arguments in arrow function.
What is arguments, super, new.target
Template String
Instead of using + to concat strings and variables, ES6 introduces back tick ** and ${} to do this. like:
`
Inheritance
In ES5, recommendation is avoid (deep) inheritance, try delegation instead. In Es6, classes provide a syntactic sugar attempting
Constants and block scoped variables.
Constants and Block Scoped
ES6 introduce block scoping. In addition to var, we have const and let.
var still means local/in-function scope. Functions are containers that can see outside from inside, but not the reverse.
const and let use {} as containers. => block scope. like:
{
let ...;
}
Block scoping is most used in loops. let is like var, const is read-only.
The const cannot be reassigned but its properties still can alter.
spread … and rest …
... Which is added in front of an variable, can serve for two purposes:
- one is to spread the content of an array or an object.
- one is to stand for unknown number of arguments when declaring a function, change them into array.
Spread …
... stand for a few items (elements of array, or property of an object).
... can kind of remove the [] of array and {} of object.
can be used in generating function argument list from an array, generating concatenating arrays/objects.
let args = [3,5];
const add = (a,b) =>a + b;
add(...args);
rest …
Javascript already have a arguments variable for each function(except arrow function). The problem is arguments is not an array.
While ... is an array, and works like an normal argument.
function print(a,b,c,...more){
;
}
Destructuring
Destructuring means extract data from {} or [] easily.
let foo = [1,2,3];
let[ a,b,c] = foo;
let myModule = {
;
}
let { , } = myModule;
Allows you to pull specific properties out of an object, especially when passing them into a function:
let jane = {firstName: 'Jane', lastName: 'Doe'};
let john = {firstName: 'John'};
function sayName({firstName, lastName = ''}){
console.log('${firstName} ${lastName}');
}
sayName(jane);
sayName(john);
More (sophisticated) examples please go to mdn. e.g. nested object destructuring, dynamic destructuring with for ... in
ES6 Modules
- Defining an ES6 module: each file is assumed to define a module and we specify its exported values using
export - Loading ES6 module:
- use
Systemin ES6 browser can load it asynchronously. - Or use
SystemJSas a polyfill. system.js
- use
TypeScript
TypeScript is a superset of ES6, Typescript must be transpiled to ES5 in most browsers One primary feature is the addition of type information
Getting Started With TypeScript
Install TypeScript using npm, then use tsc to transpile.(See book or tutorial)
TypeScript expects instance properties to be declared with a type.
property : string[];
something: any;
Working with tsc
Compile .ts to .js. Use of --module flag.
tsconfig.json let programmers write down all the compiler settings they want, and tsc uses it. Here are a few config items:
target: usually “es5”module: specifies the target moule resolution interface, which we usecommonjsdecoratorsset true since angular 2 uses a lot Webpack?
Typings
How does TypeScript interface JS modules with no type info.
*.d.ts files are definition files, which are meeant to use TypeScript to describe interfaces from javascript lib.
A utility called typings can be used to manage third party typing.
Linting
tslint tslint-loader
TypeScript Features
- Types
- Interfaces
- Shapes
- Decorators
Types
Javascript Types(programmer usually don’t need to worry about)
- boolean
- number
- string
- []
- {}
- undefined Typescript types
- enum
- any
- void Examples:
let list: number[] = [1,2];enum Color {Red,Green,Blue};
TypeScript support optional parameters:
function func(message:string, opt_message?:string){;}
TypeScript Classes
TypeScript also treat class as a type. class can have optional members.
e.g.
class Foo { foo:number; name?:string;}
class Bar {bar:string;}
class Baz {
constructor(foo: Foo, bar: Bar){}
}
let baz = new Baz(new Foo(), new Bar())
Interfaces
Two problems:
- Some times class is more than a programmer’s need
- functions in JS are “first class”, what about in TS? interface
- Interfaces are abstract descriptions of things
- can be used to represent any non-primitive JS object.
- Produce no code, but exist to describe the types to tsc. Interesting example in book.
Shapes
####
##JavaScript ToolChain
Git
###CommandLine
NodeJS
Important tool for JavaScript Developers.
npm
package.json specifies module dependencies.
Module Loading, Bundling and Build Tasks: Webpack
Webpack
- Takes modules with dependencies
- and generates static assets representing those modules
- bundle JS,CSS,HTML
- Can be extended via plugins, e.g. minification and mangling using UglifyJS plugin for webpack.
