├── .gitignore
├── README.MD
├── componnets
├── app
│ ├── app.ts
│ ├── main.ts
│ └── navbar.ts
└── index.html
├── directives
├── app
│ ├── app.ts
│ ├── directives.ts
│ ├── highlight.directive.ts
│ └── main.ts
└── index.html
├── hellowold
├── app
│ ├── app.ts
│ └── main.ts
└── index.html
├── http
├── app
│ ├── hero-data.ts
│ ├── heroes.json
│ ├── main.ts
│ ├── toh
│ │ ├── hero-list.component.ts
│ │ ├── hero.service.ts
│ │ ├── hero.ts
│ │ └── toh.component.ts
│ └── wiki
│ │ ├── wiki-smart.component.ts
│ │ ├── wiki.component.ts
│ │ └── wikipedia.service.ts
├── index.html
├── lib
│ └── web-api.js
└── styles.css
├── index.html
├── lifecycle
├── app
│ ├── app.ts
│ ├── lifecycle.ts
│ ├── main.ts
│ └── unless.directive.ts
└── index.html
├── pipes
├── app
│ ├── app.ts
│ ├── main.ts
│ ├── stateful
│ │ ├── fetch-json.pipe.ts
│ │ └── hero-list.component.ts
│ └── stateless
│ │ ├── exponential-strength.pipe.ts
│ │ └── power-booster.component.ts
├── heroes.json
└── index.html
├── router
├── app
│ ├── app.component.ts
│ ├── crisis-center
│ │ ├── crisis-center.component.ts
│ │ ├── crisis-detail.component.ts
│ │ ├── crisis-list.component.ts
│ │ └── crisis.service.ts
│ ├── dialog.service.ts
│ ├── heroes
│ │ ├── hero-detail.component.ts
│ │ ├── hero-list.component.ts
│ │ └── hero.service.ts
│ └── main.ts
├── index.html
└── styles.css
├── service
├── app
│ ├── app.component.ts
│ ├── app.ts
│ ├── hero-detail.component.ts
│ ├── hero.service.ts
│ ├── hero.ts
│ ├── main.ts
│ └── mock-heroes.ts
└── index.html
└── template-syntax
├── app
├── app.ts
└── main.ts
└── index.html
/.gitignore:
--------------------------------------------------------------------------------
1 |
2 | # IntelliJ project files
3 | .idea
4 | *.iml
5 | out
6 | gen
7 | # Created by .ignore support plugin (hsz.mobi)
8 |
--------------------------------------------------------------------------------
/README.MD:
--------------------------------------------------------------------------------
1 | ## Angular2系列教程
2 | [Angular2系列教程(一)hello world](http://liuyiqi.cn/2016/02/15/ng2-hello/)
3 |
4 | [Angular2系列教程(二)模板语法](http://liuyiqi.cn/2016/02/15/ng2-temlate/)
5 |
6 | [Angular2系列教程(三)Components](http://liuyiqi.cn/2016/02/16/ng2-component/)
7 |
8 | [Angular2系列教程(四)Attribute directives](http://liuyiqi.cn/2016/02/17/ng2-attribute-directive/)
9 |
10 | [Angular2系列教程(五)Structural directives、再谈组件生命周期](http://liuyiqi.cn/2016/02/19/ng2-structural-directive/)
11 |
12 | [Angular2系列教程(六)两种pipe:函数式编程与面向对象编程](http://liuyiqi.cn/2016/02/24/ng2-pipe/)
13 |
14 | [Angular2系列教程(七)Injectable、Promise、Interface、使用服务](http://liuyiqi.cn/2016/02/28/ng2-service/)
15 |
16 | [Angular2系列教程(八)In-memory web api、HTTP服务、依赖注入、Observable](http://liuyiqi.cn/2016/03/20/ng2-http-1/)
17 |
18 | [Angular2系列教程(九)Jsonp、URLSearchParams、中断选择数据流](http://liuyiqi.cn/2016/03/21/ng2-http-2/)
19 |
20 | [Angular2系列教程(十)两种启动方法、两个路由服务、引用类型和单例模式的妙用](http://liuyiqi.cn/2016/04/04/ng2-router-1/)
21 |
22 | [Angular2系列教程(十一)路由嵌套、路由生命周期、matrix URL notation](http://liuyiqi.cn/2016/04/04/ng2-router-2/)
23 |
24 | > 注意:该教程写于2016年2月,是基于Angular2 beta版本讲解的,与最新稳定版本有部分差异(某些API和术语),请选择性参考,并以最新的官网文档为主!
25 |
26 | ## Angular2系列教程(续)
27 |
28 | [TypeScript: Angular 2 的秘密武器(译)](http://liuyiqi.cn/2016/12/23/typescript-angular2-secret-weapon/)
29 |
--------------------------------------------------------------------------------
/componnets/app/app.ts:
--------------------------------------------------------------------------------
1 | import {Component} from 'angular2/core';
2 | import {Navbar} from './navbar';
3 |
4 | @Component({
5 | selector: "app",
6 | directives:[Navbar],
7 | template: `
8 |
9 | `
10 | })
11 | export class App {
12 | constructor() {
13 |
14 | }
15 | }
16 |
17 |
18 |
--------------------------------------------------------------------------------
/componnets/app/main.ts:
--------------------------------------------------------------------------------
1 | import {bootstrap} from 'angular2/platform/browser';
2 | import {App} from './app';
3 |
4 | bootstrap(App).catch(err => console.error(err));
5 |
6 | /*
7 | Copyright 2016 Google Inc. All Rights Reserved.
8 | Use of this source code is governed by an MIT-style license that
9 | can be found in the LICENSE file at http://angular.io/license
10 | */
--------------------------------------------------------------------------------
/componnets/app/navbar.ts:
--------------------------------------------------------------------------------
1 | import { Component} from 'angular2/core';
2 | import {NgFor} from 'angular2/common'
3 |
4 | @Component({
5 | selector: "navbar",
6 | directives: [NgFor],
7 | styles: [`
8 | li{
9 | color: gray;
10 | }
11 | `],
12 | template: `
13 |
Democratic Party presidential candidates
14 |
17 | `
18 | })
19 | export class Navbar {
20 | items: Array
21 |
22 | constructor() {
23 | this.items = [
24 | "Hillary Clinton",
25 | "Martin O'Malley",
26 | "Bernie Sanders"
27 | ]
28 | }
29 |
30 | ngOnInit() {
31 | console.log('[Component] navbar onInit');
32 | }
33 | }
34 |
35 |
36 |
--------------------------------------------------------------------------------
/componnets/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Angular 2 Demo
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
26 |
27 |
28 |
29 | Loading...
30 |
31 |
32 |
33 |
34 |
--------------------------------------------------------------------------------
/directives/app/app.ts:
--------------------------------------------------------------------------------
1 | import {Component} from 'angular2/core';
2 | import {Redify} from './directives';
3 | import {HighlightDirective} from './highlight.directive';
4 |
5 | @Component({
6 | selector: "app",
7 | directives:[Redify,HighlightDirective],
8 | template: `
9 | redify:
10 | hello,lewis
11 | myHighlight:
12 |
13 | Green
14 | Yellow
15 | Cyan
16 |
17 | Highlight me!
18 | Highlight me too!
19 | `
20 | })
21 | export class App {
22 | constructor() {
23 |
24 | }
25 | }
26 |
27 |
28 |
--------------------------------------------------------------------------------
/directives/app/directives.ts:
--------------------------------------------------------------------------------
1 | import {Directive, ElementRef, Renderer} from 'angular2/core';
2 |
3 | @Directive({
4 | selector: '[redify]'
5 | })
6 | export class Redify {
7 |
8 | constructor(private _element: ElementRef, private renderer: Renderer) {
9 | renderer.setElementStyle(_element.nativeElement, 'color', 'red');
10 | }
11 | }
--------------------------------------------------------------------------------
/directives/app/highlight.directive.ts:
--------------------------------------------------------------------------------
1 | import {Directive, ElementRef, Input} from 'angular2/core';
2 |
3 | @Directive({
4 | selector: '[myHighlight]',
5 | host: {
6 | '(mouseenter)': 'onMouseEnter()',
7 | '(mouseleave)': 'onMouseLeave()'
8 | }
9 | })
10 |
11 | export class HighlightDirective {
12 | /*
13 | @Input() myHighlight: string;
14 | */
15 | @Input('myHighlight') highlightColor: string;
16 |
17 | private _defaultColor = 'red';
18 | @Input() set defaultColor(colorName:string){
19 | this._defaultColor = colorName || this._defaultColor;
20 | }
21 |
22 | constructor(private el: ElementRef) { }
23 |
24 | onMouseEnter() { this._highlight(this.highlightColor || this._defaultColor); }
25 | onMouseLeave() { this._highlight(null); }
26 |
27 | private _highlight(color:string) {
28 | this.el.nativeElement.style.backgroundColor = color;
29 | }
30 | }
31 |
32 | /*
33 | Copyright 2016 Google Inc. All Rights Reserved.
34 | Use of this source code is governed by an MIT-style license that
35 | can be found in the LICENSE file at http://angular.io/license
36 | */
--------------------------------------------------------------------------------
/directives/app/main.ts:
--------------------------------------------------------------------------------
1 | import {bootstrap} from 'angular2/platform/browser';
2 | import {App} from './app';
3 |
4 | bootstrap(App).catch(err => console.error(err));
5 |
6 | /*
7 | Copyright 2016 Google Inc. All Rights Reserved.
8 | Use of this source code is governed by an MIT-style license that
9 | can be found in the LICENSE file at http://angular.io/license
10 | */
--------------------------------------------------------------------------------
/directives/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Angular 2 Demo
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
26 |
27 |
28 |
29 | Loading...
30 |
31 |
32 |
33 |
34 |
--------------------------------------------------------------------------------
/hellowold/app/app.ts:
--------------------------------------------------------------------------------
1 | import {Component} from 'angular2/core';
2 |
3 | @Component({
4 | selector: 'app',
5 | template: `
6 | Hello, {{name}}!
7 | Say hello to:
8 | `
9 | })
10 | export class App {
11 | name: string = 'World';
12 | }
13 |
--------------------------------------------------------------------------------
/hellowold/app/main.ts:
--------------------------------------------------------------------------------
1 | import {bootstrap} from 'angular2/platform/browser';
2 | import {App} from './app';
3 |
4 | bootstrap(App).catch(err => console.error(err));
5 |
6 | /*
7 | Copyright 2016 Google Inc. All Rights Reserved.
8 | Use of this source code is governed by an MIT-style license that
9 | can be found in the LICENSE file at http://angular.io/license
10 | */
--------------------------------------------------------------------------------
/hellowold/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Angular 2 Demo
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
26 |
27 |
28 |
29 | Loading...
30 |
31 |
32 |
33 |
34 |
--------------------------------------------------------------------------------
/http/app/hero-data.ts:
--------------------------------------------------------------------------------
1 | export class HeroData {
2 | createDb() {
3 | let heroes = [
4 | { "id": "1", "name": "Windstorm" },
5 | { "id": "2", "name": "Bombasto" },
6 | { "id": "3", "name": "Magneta" },
7 | { "id": "4", "name": "Tornado" }
8 | ];
9 | return {heroes};
10 | }
11 | }
12 |
13 |
14 | /*
15 | Copyright 2016 Google Inc. All Rights Reserved.
16 | Use of this source code is governed by an MIT-style license that
17 | can be found in the LICENSE file at http://angular.io/license
18 | */
--------------------------------------------------------------------------------
/http/app/heroes.json:
--------------------------------------------------------------------------------
1 | {
2 | "data": [
3 | { "id": "1", "name": "Windstorm" },
4 | { "id": "2", "name": "Bombasto" },
5 | { "id": "3", "name": "Magneta" },
6 | { "id": "4", "name": "Tornado" }
7 | ]
8 | }
9 |
--------------------------------------------------------------------------------
/http/app/main.ts:
--------------------------------------------------------------------------------
1 | import {bootstrap} from 'angular2/platform/browser';
2 |
3 | // Add all operators to Observable
4 | import 'rxjs/Rx';
5 |
6 | import {WikiComponent} from './wiki/wiki.component';
7 | import {WikiSmartComponent} from './wiki/wiki-smart.component';
8 | import {TohComponent} from './toh/toh.component';
9 |
10 | bootstrap(WikiComponent);
11 | bootstrap(WikiSmartComponent);
12 | bootstrap(TohComponent);
13 |
14 | /*
15 | Copyright 2016 Google Inc. All Rights Reserved.
16 | Use of this source code is governed by an MIT-style license that
17 | can be found in the LICENSE file at http://angular.io/license
18 | */
--------------------------------------------------------------------------------
/http/app/toh/hero-list.component.ts:
--------------------------------------------------------------------------------
1 | import {Component, OnInit} from 'angular2/core';
2 | import {Hero} from './hero';
3 | import {HeroService} from './hero.service';
4 |
5 | @Component({
6 | selector: 'hero-list',
7 | template: `
8 | Heroes:
9 |
10 | -
11 | {{ hero.name }}
12 |
13 |
14 | New Hero:
15 |
16 |
19 | {{errorMessage}}
20 | `,
21 | styles: ['.error {color:red;}']
22 | })
23 | export class HeroListComponent implements OnInit {
24 |
25 | constructor (private _heroService: HeroService) {}
26 |
27 | errorMessage: string;
28 | heroes:Hero[];
29 |
30 | ngOnInit() { this.getHeroes(); }
31 |
32 | getHeroes() {
33 | this._heroService.getHeroes()
34 | .subscribe(
35 | heroes => this.heroes = heroes,
36 | error => this.errorMessage = error);
37 | }
38 |
39 | addHero (name: string) {
40 | if (!name) {return;}
41 | this._heroService.addHero(name)
42 | .subscribe(
43 | hero => this.heroes.push(hero),
44 | error => this.errorMessage = error);
45 | }
46 | }
47 |
48 |
49 | /*
50 | Copyright 2016 Google Inc. All Rights Reserved.
51 | Use of this source code is governed by an MIT-style license that
52 | can be found in the LICENSE file at http://angular.io/license
53 | */
--------------------------------------------------------------------------------
/http/app/toh/hero.service.ts:
--------------------------------------------------------------------------------
1 |
2 | import {Injectable} from 'angular2/core';
3 | import {Http, Response} from 'angular2/http';
4 | import {Headers, RequestOptions} from 'angular2/http';
5 | import {Hero} from './hero';
6 | import {Observable} from 'rxjs/Observable';
7 |
8 | @Injectable()
9 | export class HeroService {
10 | constructor (private http: Http) {}
11 |
12 | /*
13 | private _heroesUrl = 'app/heroes.json'; // URL to JSON file
14 | */
15 |
16 | private _heroesUrl = 'app/heroes'; // URL to web api
17 |
18 | getHeroes () {
19 | return this.http.get(this._heroesUrl)
20 | .map(res => res.json().data)
21 | .do(data => console.log(data)) // eyeball results in the console
22 | .catch(this.handleError);
23 | }
24 |
25 | addHero (name: string) : Observable {
26 |
27 | let body = JSON.stringify({ name });
28 | let headers = new Headers({ 'Content-Type': 'application/json' });
29 | let options = new RequestOptions({ headers: headers });
30 |
31 | return this.http.post(this._heroesUrl, body, options)
32 | .map(res => res.json().data)
33 | .catch(this.handleError)
34 | }
35 |
36 | private handleError (error: Response) {
37 | // in a real world app, we may send the error to some remote logging infrastructure
38 | // instead of just logging it to the console
39 | console.error(error);
40 | return Observable.throw(error.json().error || 'Server error');
41 | }
42 | }
43 |
44 |
45 | /*
46 | Copyright 2016 Google Inc. All Rights Reserved.
47 | Use of this source code is governed by an MIT-style license that
48 | can be found in the LICENSE file at http://angular.io/license
49 | */
--------------------------------------------------------------------------------
/http/app/toh/hero.ts:
--------------------------------------------------------------------------------
1 | export class Hero {
2 | constructor(
3 | public id:number,
4 | public name:string) { }
5 | }
6 |
7 |
8 | /*
9 | Copyright 2016 Google Inc. All Rights Reserved.
10 | Use of this source code is governed by an MIT-style license that
11 | can be found in the LICENSE file at http://angular.io/license
12 | */
--------------------------------------------------------------------------------
/http/app/toh/toh.component.ts:
--------------------------------------------------------------------------------
1 |
2 | import {Component} from 'angular2/core';
3 | import {HTTP_PROVIDERS} from 'angular2/http';
4 |
5 | import {Hero} from './hero';
6 | import {HeroListComponent} from './hero-list.component';
7 | import {HeroService} from './hero.service';
8 |
9 | import {provide} from 'angular2/core';
10 | import {XHRBackend} from 'angular2/http';
11 |
12 | // in-memory web api imports
13 | import {InMemoryBackendService,
14 | SEED_DATA} from 'a2-in-memory-web-api/core';
15 | import {HeroData} from '../hero-data';
16 |
17 | @Component({
18 | selector: 'my-toh',
19 | template: `
20 | Tour of Heroes
21 |
22 | `,
23 | directives:[HeroListComponent],
24 | providers: [
25 | HTTP_PROVIDERS,
26 | HeroService,
27 | // in-memory web api providers
28 | provide(XHRBackend, { useClass: InMemoryBackendService }), // in-mem server
29 | provide(SEED_DATA, { useClass: HeroData }) // in-mem server data
30 | ]
31 | })
32 | export class TohComponent { }
33 |
34 |
35 | /*
36 | Copyright 2016 Google Inc. All Rights Reserved.
37 | Use of this source code is governed by an MIT-style license that
38 | can be found in the LICENSE file at http://angular.io/license
39 | */
--------------------------------------------------------------------------------
/http/app/wiki/wiki-smart.component.ts:
--------------------------------------------------------------------------------
1 | import {Component} from 'angular2/core';
2 | import {JSONP_PROVIDERS} from 'angular2/http';
3 | import {Observable} from 'rxjs/Observable';
4 | import {Subject} from 'rxjs/Subject';
5 |
6 | import {WikipediaService} from './wikipedia.service';
7 |
8 | @Component({
9 | selector: 'my-wiki-smart',
10 | template: `
11 | Smarter Wikipedia Demo
12 | Fetches when typing stops
13 |
14 |
15 |
16 |
19 | `,
20 | providers:[JSONP_PROVIDERS, WikipediaService]
21 | })
22 | export class WikiSmartComponent {
23 |
24 | constructor (private _wikipediaService: WikipediaService) { }
25 |
26 | private _searchTermStream = new Subject();
27 |
28 | search(term:string) { this._searchTermStream.next(term); }
29 |
30 | items:Observable = this._searchTermStream
31 | .debounceTime(300)
32 | .distinctUntilChanged()
33 | .switchMap((term:string) => this._wikipediaService.search(term));
34 | }
35 |
36 |
37 | /*
38 | Copyright 2016 Google Inc. All Rights Reserved.
39 | Use of this source code is governed by an MIT-style license that
40 | can be found in the LICENSE file at http://angular.io/license
41 | */
--------------------------------------------------------------------------------
/http/app/wiki/wiki.component.ts:
--------------------------------------------------------------------------------
1 | import {Component} from 'angular2/core';
2 | import {JSONP_PROVIDERS} from 'angular2/http';
3 | import {Observable} from 'rxjs/Observable';
4 |
5 | import {WikipediaService} from './wikipedia.service';
6 |
7 | @Component({
8 | selector: 'my-wiki',
9 | template: `
10 | Wikipedia Demo
11 | Fetches after each keystroke
12 |
13 |
14 |
15 |
18 | `,
19 | providers:[JSONP_PROVIDERS, WikipediaService]
20 | })
21 | export class WikiComponent {
22 |
23 | constructor (private _wikipediaService: WikipediaService) {}
24 |
25 | items: Observable;
26 |
27 | search (term: string) {
28 | this.items = this._wikipediaService.search(term);
29 | }
30 | }
31 |
32 |
33 | /*
34 | Copyright 2016 Google Inc. All Rights Reserved.
35 | Use of this source code is governed by an MIT-style license that
36 | can be found in the LICENSE file at http://angular.io/license
37 | */
--------------------------------------------------------------------------------
/http/app/wiki/wikipedia.service.ts:
--------------------------------------------------------------------------------
1 | import {Injectable} from 'angular2/core';
2 | import {Jsonp, URLSearchParams} from 'angular2/http';
3 |
4 | @Injectable()
5 | export class WikipediaService {
6 | constructor(private jsonp: Jsonp) {}
7 |
8 | search (term: string) {
9 |
10 | let wikiUrl = 'http://en.wikipedia.org/w/api.php';
11 |
12 | var params = new URLSearchParams();
13 | params.set('search', term); // the user's search value
14 | params.set('action', 'opensearch');
15 | params.set('format', 'json');
16 | params.set('callback', 'JSONP_CALLBACK');
17 |
18 | // TODO: Add error handling
19 | return this.jsonp
20 | .get(wikiUrl, { search: params })
21 | .map(request => request.json()[1]);
22 | }
23 | }
24 |
25 |
26 | /*
27 | Copyright 2016 Google Inc. All Rights Reserved.
28 | Use of this source code is governed by an MIT-style license that
29 | can be found in the LICENSE file at http://angular.io/license
30 | */
--------------------------------------------------------------------------------
/http/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Angular 2 Http Demo
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
31 |
32 |
33 |
34 |
35 | ToH Loading...
36 | Wiki Loading...
37 | WikiSmart Loading...
38 |
39 |
40 |
41 |
42 |
43 |
--------------------------------------------------------------------------------
/http/lib/web-api.js:
--------------------------------------------------------------------------------
1 | System.register("a2-in-memory-web-api/in-memory-backend.service", ["angular2/core", "angular2/http", "rxjs/Observable", "rxjs/add/operator/delay", "./http-status-codes"], function(exports_1, context_1) {
2 | "use strict";
3 | var __moduleName = context_1 && context_1.id;
4 | var __decorate = (this && this.__decorate) || function(decorators, target, key, desc) {
5 | var c = arguments.length,
6 | r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc,
7 | d;
8 | if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
9 | r = Reflect.decorate(decorators, target, key, desc);
10 | else
11 | for (var i = decorators.length - 1; i >= 0; i--)
12 | if (d = decorators[i])
13 | r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
14 | return c > 3 && r && Object.defineProperty(target, key, r), r;
15 | };
16 | var __metadata = (this && this.__metadata) || function(k, v) {
17 | if (typeof Reflect === "object" && typeof Reflect.metadata === "function")
18 | return Reflect.metadata(k, v);
19 | };
20 | var __param = (this && this.__param) || function(paramIndex, decorator) {
21 | return function(target, key) {
22 | decorator(target, key, paramIndex);
23 | };
24 | };
25 | var core_1,
26 | http_1,
27 | Observable_1,
28 | http_status_codes_1;
29 | var SEED_DATA,
30 | InMemoryBackendConfig,
31 | isSuccess,
32 | InMemoryBackendService;
33 | return {
34 | setters: [function(core_1_1) {
35 | core_1 = core_1_1;
36 | }, function(http_1_1) {
37 | http_1 = http_1_1;
38 | }, function(Observable_1_1) {
39 | Observable_1 = Observable_1_1;
40 | }, function(_1) {}, function(http_status_codes_1_1) {
41 | http_status_codes_1 = http_status_codes_1_1;
42 | }],
43 | execute: function() {
44 | exports_1("SEED_DATA", SEED_DATA = new core_1.OpaqueToken('seedData'));
45 | InMemoryBackendConfig = (function() {
46 | function InMemoryBackendConfig(config) {
47 | if (config === void 0) {
48 | config = {};
49 | }
50 | Object.assign(this, {
51 | defaultResponseOptions: new http_1.BaseResponseOptions(),
52 | delay: 500,
53 | delete404: false
54 | }, config);
55 | }
56 | return InMemoryBackendConfig;
57 | }());
58 | exports_1("InMemoryBackendConfig", InMemoryBackendConfig);
59 | exports_1("isSuccess", isSuccess = function(status) {
60 | return (status >= 200 && status < 300);
61 | });
62 | InMemoryBackendService = (function() {
63 | function InMemoryBackendService(_seedData, config) {
64 | this._seedData = _seedData;
65 | this._config = new InMemoryBackendConfig();
66 | this._resetDb();
67 | var loc = this._getLocation('./');
68 | this._config.host = loc.host;
69 | this._config.rootPath = loc.pathname;
70 | Object.assign(this._config, config);
71 | }
72 | InMemoryBackendService.prototype.createConnection = function(req) {
73 | var res = this._handleRequest(req);
74 | var response = new Observable_1.Observable(function(responseObserver) {
75 | if (isSuccess(res.status)) {
76 | responseObserver.next(res);
77 | responseObserver.complete();
78 | } else {
79 | responseObserver.error(res);
80 | }
81 | return function() {};
82 | });
83 | response = response.delay(this._config.delay || 500);
84 | return {response: response};
85 | };
86 | InMemoryBackendService.prototype._handleRequest = function(req) {
87 | var _a = this._parseUrl(req.url),
88 | base = _a.base,
89 | collectionName = _a.collectionName,
90 | id = _a.id,
91 | resourceUrl = _a.resourceUrl;
92 | var reqInfo = {
93 | req: req,
94 | base: base,
95 | collection: this._db[collectionName],
96 | collectionName: collectionName,
97 | headers: new http_1.Headers({"Content-Type": "application/json"}),
98 | id: this._parseId(id),
99 | resourceUrl: resourceUrl
100 | };
101 | var options;
102 | try {
103 | if ("commands" === reqInfo.base.toLowerCase()) {
104 | options = this._commands(reqInfo);
105 | } else if (reqInfo.collection) {
106 | switch (req.method) {
107 | case http_1.RequestMethod.Get:
108 | options = this._get(reqInfo);
109 | break;
110 | case http_1.RequestMethod.Post:
111 | options = this._post(reqInfo);
112 | break;
113 | case http_1.RequestMethod.Put:
114 | options = this._put(reqInfo);
115 | break;
116 | case http_1.RequestMethod.Delete:
117 | options = this._delete(reqInfo);
118 | break;
119 | default:
120 | options = this._createErrorResponse(http_status_codes_1.STATUS.METHOD_NOT_ALLOWED, "Method not allowed");
121 | break;
122 | }
123 | } else {
124 | options = this._createErrorResponse(http_status_codes_1.STATUS.NOT_FOUND, "Collection \"" + collectionName + "\" not found");
125 | }
126 | } catch (error) {
127 | var err = error.message || error;
128 | options = this._createErrorResponse(http_status_codes_1.STATUS.INTERNAL_SERVER_ERROR, "" + err);
129 | }
130 | options = this._setStatusText(options);
131 | if (this._config.defaultResponseOptions) {
132 | options = this._config.defaultResponseOptions.merge(options);
133 | }
134 | return new http_1.Response(options);
135 | };
136 | InMemoryBackendService.prototype._clone = function(data) {
137 | return JSON.parse(JSON.stringify(data));
138 | };
139 | InMemoryBackendService.prototype._commands = function(reqInfo) {
140 | var command = reqInfo.collectionName.toLowerCase();
141 | var method = reqInfo.req.method;
142 | var options;
143 | switch (command) {
144 | case 'resetdb':
145 | this._resetDb();
146 | options = new http_1.ResponseOptions({status: http_status_codes_1.STATUS.OK});
147 | break;
148 | case 'config':
149 | if (method === http_1.RequestMethod.Get) {
150 | options = new http_1.ResponseOptions({
151 | body: this._clone(this._config),
152 | status: http_status_codes_1.STATUS.OK
153 | });
154 | } else {
155 | var body = JSON.parse(reqInfo.req.text() || '{}');
156 | Object.assign(this._config, body);
157 | options = new http_1.ResponseOptions({status: http_status_codes_1.STATUS.NO_CONTENT});
158 | }
159 | default:
160 | options = this._createErrorResponse(http_status_codes_1.STATUS.INTERNAL_SERVER_ERROR, "Unknown command \"" + command + "\"");
161 | }
162 | return options;
163 | };
164 | InMemoryBackendService.prototype._createErrorResponse = function(status, message) {
165 | return new http_1.ResponseOptions({
166 | body: {"error": "" + message},
167 | headers: new http_1.Headers({"Content-Type": "application/json"}),
168 | status: status
169 | });
170 | };
171 | InMemoryBackendService.prototype._delete = function(_a) {
172 | var id = _a.id,
173 | collection = _a.collection,
174 | collectionName = _a.collectionName,
175 | headers = _a.headers,
176 | req = _a.req;
177 | if (!id) {
178 | return this._createErrorResponse(http_status_codes_1.STATUS.NOT_FOUND, "Missing \"" + collectionName + "\" id");
179 | }
180 | var exists = this._removeById(collection, id);
181 | return new http_1.ResponseOptions({
182 | headers: headers,
183 | status: (exists || !this._config.delete404) ? http_status_codes_1.STATUS.NO_CONTENT : http_status_codes_1.STATUS.NOT_FOUND
184 | });
185 | };
186 | InMemoryBackendService.prototype._findById = function(collection, id) {
187 | return collection.find(function(item) {
188 | return item.id === id;
189 | });
190 | };
191 | InMemoryBackendService.prototype._genId = function(collection) {
192 | var maxId = 0;
193 | collection.reduce(function(prev, item) {
194 | maxId = Math.max(maxId, typeof item.id === 'number' ? item.id : maxId);
195 | }, null);
196 | return maxId + 1;
197 | };
198 | InMemoryBackendService.prototype._get = function(_a) {
199 | var id = _a.id,
200 | collection = _a.collection,
201 | collectionName = _a.collectionName,
202 | headers = _a.headers;
203 | var data = (id) ? this._findById(collection, id) : collection;
204 | if (!data) {
205 | return this._createErrorResponse(http_status_codes_1.STATUS.NOT_FOUND, "\"" + collectionName + "\" with id=\"" + id + "\" not found");
206 | }
207 | return new http_1.ResponseOptions({
208 | body: {data: this._clone(data)},
209 | headers: headers,
210 | status: http_status_codes_1.STATUS.OK
211 | });
212 | };
213 | InMemoryBackendService.prototype._getLocation = function(href) {
214 | var l = document.createElement('a');
215 | l.href = href;
216 | return l;
217 | };
218 | ;
219 | InMemoryBackendService.prototype._indexOf = function(collection, id) {
220 | return collection.findIndex(function(item) {
221 | return item.id === id;
222 | });
223 | };
224 | InMemoryBackendService.prototype._parseId = function(id) {
225 | if (!id) {
226 | return null;
227 | }
228 | var idNum = parseInt(id, 10);
229 | return isNaN(idNum) ? id : idNum;
230 | };
231 | InMemoryBackendService.prototype._parseUrl = function(url) {
232 | try {
233 | var loc = this._getLocation(url);
234 | var drop = this._config.rootPath.length;
235 | var urlRoot = '';
236 | if (loc.host !== this._config.host) {
237 | drop = 1;
238 | urlRoot = loc.protocol + '//' + loc.host + '/';
239 | }
240 | var path = loc.pathname.substring(drop);
241 | var _a = path.split('/'),
242 | base = _a[0],
243 | collectionName = _a[1],
244 | id = _a[2];
245 | var resourceUrl = urlRoot + base + '/' + collectionName + '/';
246 | collectionName = collectionName.split('.')[0];
247 | return {
248 | base: base,
249 | id: id,
250 | collectionName: collectionName,
251 | resourceUrl: resourceUrl
252 | };
253 | } catch (err) {
254 | var msg = "unable to parse url \"" + url + "\"; original error: " + err.message;
255 | throw new Error(msg);
256 | }
257 | };
258 | InMemoryBackendService.prototype._post = function(_a) {
259 | var collection = _a.collection,
260 | collectionName = _a.collectionName,
261 | headers = _a.headers,
262 | id = _a.id,
263 | req = _a.req,
264 | resourceUrl = _a.resourceUrl;
265 | var item = JSON.parse(req.text());
266 | if (!item.id) {
267 | item.id = id || this._genId(collection);
268 | }
269 | id = item.id;
270 | var existingIx = this._indexOf(collection, id);
271 | if (existingIx > -1) {
272 | collection[existingIx] = item;
273 | return new http_1.ResponseOptions({
274 | headers: headers,
275 | status: http_status_codes_1.STATUS.NO_CONTENT
276 | });
277 | } else {
278 | collection.push(item);
279 | headers.set('Location', resourceUrl + '/' + id);
280 | return new http_1.ResponseOptions({
281 | headers: headers,
282 | body: {data: this._clone(item)},
283 | status: http_status_codes_1.STATUS.CREATED
284 | });
285 | }
286 | };
287 | InMemoryBackendService.prototype._put = function(_a) {
288 | var id = _a.id,
289 | collection = _a.collection,
290 | collectionName = _a.collectionName,
291 | headers = _a.headers,
292 | req = _a.req;
293 | var item = JSON.parse(req.text());
294 | if (!id) {
295 | return this._createErrorResponse(http_status_codes_1.STATUS.NOT_FOUND, "Missing \"" + collectionName + "\" id");
296 | }
297 | if (id !== item.id) {
298 | return this._createErrorResponse(http_status_codes_1.STATUS.BAD_REQUEST, "\"" + collectionName + "\" id does not match item.id");
299 | }
300 | var existingIx = this._indexOf(collection, id);
301 | if (existingIx > -1) {
302 | collection[existingIx] = item;
303 | return new http_1.ResponseOptions({
304 | headers: headers,
305 | status: http_status_codes_1.STATUS.NO_CONTENT
306 | });
307 | } else {
308 | collection.push(item);
309 | return new http_1.ResponseOptions({
310 | body: {data: this._clone(item)},
311 | headers: headers,
312 | status: http_status_codes_1.STATUS.CREATED
313 | });
314 | }
315 | };
316 | InMemoryBackendService.prototype._removeById = function(collection, id) {
317 | var ix = this._indexOf(collection, id);
318 | if (ix > -1) {
319 | collection.splice(ix, 1);
320 | return true;
321 | }
322 | return false;
323 | };
324 | InMemoryBackendService.prototype._resetDb = function() {
325 | this._db = this._seedData.createDb();
326 | };
327 | InMemoryBackendService.prototype._setStatusText = function(options) {
328 | try {
329 | var statusCode = http_status_codes_1.STATUS_CODE_INFO[options.status];
330 | options['statusText'] = statusCode ? statusCode.text : 'Unknown Status';
331 | return options;
332 | } catch (err) {
333 | return new http_1.ResponseOptions({
334 | status: http_status_codes_1.STATUS.INTERNAL_SERVER_ERROR,
335 | statusText: 'Invalid Server Operation'
336 | });
337 | }
338 | };
339 | InMemoryBackendService = __decorate([__param(0, core_1.Inject(SEED_DATA)), __param(1, core_1.Inject(InMemoryBackendConfig)), __param(1, core_1.Optional()), __metadata('design:paramtypes', [Object, Object])], InMemoryBackendService);
340 | return InMemoryBackendService;
341 | }());
342 | exports_1("InMemoryBackendService", InMemoryBackendService);
343 | }
344 | };
345 | });
346 |
347 | System.register("a2-in-memory-web-api/http-status-codes", [], function(exports_1, context_1) {
348 | "use strict";
349 | var __moduleName = context_1 && context_1.id;
350 | var STATUS,
351 | STATUS_CODE_INFO;
352 | return {
353 | setters: [],
354 | execute: function() {
355 | exports_1("STATUS", STATUS = {
356 | CONTINUE: 100,
357 | SWITCHING_PROTOCOLS: 101,
358 | OK: 200,
359 | CREATED: 201,
360 | ACCEPTED: 202,
361 | NON_AUTHORITATIVE_INFORMATION: 203,
362 | NO_CONTENT: 204,
363 | RESET_CONTENT: 205,
364 | PARTIAL_CONTENT: 206,
365 | MULTIPLE_CHOICES: 300,
366 | MOVED_PERMANTENTLY: 301,
367 | FOUND: 302,
368 | SEE_OTHER: 303,
369 | NOT_MODIFIED: 304,
370 | USE_PROXY: 305,
371 | TEMPORARY_REDIRECT: 307,
372 | BAD_REQUEST: 400,
373 | UNAUTHORIZED: 401,
374 | PAYMENT_REQUIRED: 402,
375 | FORBIDDEN: 403,
376 | NOT_FOUND: 404,
377 | METHOD_NOT_ALLOWED: 405,
378 | NOT_ACCEPTABLE: 406,
379 | PROXY_AUTHENTICATION_REQUIRED: 407,
380 | REQUEST_TIMEOUT: 408,
381 | CONFLICT: 409,
382 | GONE: 410,
383 | LENGTH_REQUIRED: 411,
384 | PRECONDITION_FAILED: 412,
385 | PAYLOAD_TO_LARGE: 413,
386 | URI_TOO_LONG: 414,
387 | UNSUPPORTED_MEDIA_TYPE: 415,
388 | RANGE_NOT_SATISFIABLE: 416,
389 | EXPECTATION_FAILED: 417,
390 | IM_A_TEAPOT: 418,
391 | UPGRADE_REQUIRED: 426,
392 | INTERNAL_SERVER_ERROR: 500,
393 | NOT_IMPLEMENTED: 501,
394 | BAD_GATEWAY: 502,
395 | SERVICE_UNAVAILABLE: 503,
396 | GATEWAY_TIMEOUT: 504,
397 | HTTP_VERSION_NOT_SUPPORTED: 505,
398 | PROCESSING: 102,
399 | MULTI_STATUS: 207,
400 | IM_USED: 226,
401 | PERMANENT_REDIRECT: 308,
402 | UNPROCESSABLE_ENTRY: 422,
403 | LOCKED: 423,
404 | FAILED_DEPENDENCY: 424,
405 | PRECONDITION_REQUIRED: 428,
406 | TOO_MANY_REQUESTS: 429,
407 | REQUEST_HEADER_FIELDS_TOO_LARGE: 431,
408 | UNAVAILABLE_FOR_LEGAL_REASONS: 451,
409 | VARIANT_ALSO_NEGOTIATES: 506,
410 | INSUFFICIENT_STORAGE: 507,
411 | NETWORK_AUTHENTICATION_REQUIRED: 511
412 | });
413 | exports_1("STATUS_CODE_INFO", STATUS_CODE_INFO = {
414 | "100": {
415 | "code": 100,
416 | "text": "Continue",
417 | "description": "\"The initial part of a request has been received and has not yet been rejected by the server.\"",
418 | "spec_title": "RFC7231#6.2.1",
419 | "spec_href": "http://tools.ietf.org/html/rfc7231#section-6.2.1"
420 | },
421 | "101": {
422 | "code": 101,
423 | "text": "Switching Protocols",
424 | "description": "\"The server understands and is willing to comply with the client's request, via the Upgrade header field, for a change in the application protocol being used on this connection.\"",
425 | "spec_title": "RFC7231#6.2.2",
426 | "spec_href": "http://tools.ietf.org/html/rfc7231#section-6.2.2"
427 | },
428 | "200": {
429 | "code": 200,
430 | "text": "OK",
431 | "description": "\"The request has succeeded.\"",
432 | "spec_title": "RFC7231#6.3.1",
433 | "spec_href": "http://tools.ietf.org/html/rfc7231#section-6.3.1"
434 | },
435 | "201": {
436 | "code": 201,
437 | "text": "Created",
438 | "description": "\"The request has been fulfilled and has resulted in one or more new resources being created.\"",
439 | "spec_title": "RFC7231#6.3.2",
440 | "spec_href": "http://tools.ietf.org/html/rfc7231#section-6.3.2"
441 | },
442 | "202": {
443 | "code": 202,
444 | "text": "Accepted",
445 | "description": "\"The request has been accepted for processing, but the processing has not been completed.\"",
446 | "spec_title": "RFC7231#6.3.3",
447 | "spec_href": "http://tools.ietf.org/html/rfc7231#section-6.3.3"
448 | },
449 | "203": {
450 | "code": 203,
451 | "text": "Non-Authoritative Information",
452 | "description": "\"The request was successful but the enclosed payload has been modified from that of the origin server's 200 (OK) response by a transforming proxy.\"",
453 | "spec_title": "RFC7231#6.3.4",
454 | "spec_href": "http://tools.ietf.org/html/rfc7231#section-6.3.4"
455 | },
456 | "204": {
457 | "code": 204,
458 | "text": "No Content",
459 | "description": "\"The server has successfully fulfilled the request and that there is no additional content to send in the response payload body.\"",
460 | "spec_title": "RFC7231#6.3.5",
461 | "spec_href": "http://tools.ietf.org/html/rfc7231#section-6.3.5"
462 | },
463 | "205": {
464 | "code": 205,
465 | "text": "Reset Content",
466 | "description": "\"The server has fulfilled the request and desires that the user agent reset the \"document view\", which caused the request to be sent, to its original state as received from the origin server.\"",
467 | "spec_title": "RFC7231#6.3.6",
468 | "spec_href": "http://tools.ietf.org/html/rfc7231#section-6.3.6"
469 | },
470 | "206": {
471 | "code": 206,
472 | "text": "Partial Content",
473 | "description": "\"The server is successfully fulfilling a range request for the target resource by transferring one or more parts of the selected representation that correspond to the satisfiable ranges found in the requests's Range header field.\"",
474 | "spec_title": "RFC7233#4.1",
475 | "spec_href": "http://tools.ietf.org/html/rfc7233#section-4.1"
476 | },
477 | "300": {
478 | "code": 300,
479 | "text": "Multiple Choices",
480 | "description": "\"The target resource has more than one representation, each with its own more specific identifier, and information about the alternatives is being provided so that the user (or user agent) can select a preferred representation by redirecting its request to one or more of those identifiers.\"",
481 | "spec_title": "RFC7231#6.4.1",
482 | "spec_href": "http://tools.ietf.org/html/rfc7231#section-6.4.1"
483 | },
484 | "301": {
485 | "code": 301,
486 | "text": "Moved Permanently",
487 | "description": "\"The target resource has been assigned a new permanent URI and any future references to this resource ought to use one of the enclosed URIs.\"",
488 | "spec_title": "RFC7231#6.4.2",
489 | "spec_href": "http://tools.ietf.org/html/rfc7231#section-6.4.2"
490 | },
491 | "302": {
492 | "code": 302,
493 | "text": "Found",
494 | "description": "\"The target resource resides temporarily under a different URI.\"",
495 | "spec_title": "RFC7231#6.4.3",
496 | "spec_href": "http://tools.ietf.org/html/rfc7231#section-6.4.3"
497 | },
498 | "303": {
499 | "code": 303,
500 | "text": "See Other",
501 | "description": "\"The server is redirecting the user agent to a different resource, as indicated by a URI in the Location header field, that is intended to provide an indirect response to the original request.\"",
502 | "spec_title": "RFC7231#6.4.4",
503 | "spec_href": "http://tools.ietf.org/html/rfc7231#section-6.4.4"
504 | },
505 | "304": {
506 | "code": 304,
507 | "text": "Not Modified",
508 | "description": "\"A conditional GET request has been received and would have resulted in a 200 (OK) response if it were not for the fact that the condition has evaluated to false.\"",
509 | "spec_title": "RFC7232#4.1",
510 | "spec_href": "http://tools.ietf.org/html/rfc7232#section-4.1"
511 | },
512 | "305": {
513 | "code": 305,
514 | "text": "Use Proxy",
515 | "description": "*deprecated*",
516 | "spec_title": "RFC7231#6.4.5",
517 | "spec_href": "http://tools.ietf.org/html/rfc7231#section-6.4.5"
518 | },
519 | "307": {
520 | "code": 307,
521 | "text": "Temporary Redirect",
522 | "description": "\"The target resource resides temporarily under a different URI and the user agent MUST NOT change the request method if it performs an automatic redirection to that URI.\"",
523 | "spec_title": "RFC7231#6.4.7",
524 | "spec_href": "http://tools.ietf.org/html/rfc7231#section-6.4.7"
525 | },
526 | "400": {
527 | "code": 400,
528 | "text": "Bad Request",
529 | "description": "\"The server cannot or will not process the request because the received syntax is invalid, nonsensical, or exceeds some limitation on what the server is willing to process.\"",
530 | "spec_title": "RFC7231#6.5.1",
531 | "spec_href": "http://tools.ietf.org/html/rfc7231#section-6.5.1"
532 | },
533 | "401": {
534 | "code": 401,
535 | "text": "Unauthorized",
536 | "description": "\"The request has not been applied because it lacks valid authentication credentials for the target resource.\"",
537 | "spec_title": "RFC7235#6.3.1",
538 | "spec_href": "http://tools.ietf.org/html/rfc7235#section-3.1"
539 | },
540 | "402": {
541 | "code": 402,
542 | "text": "Payment Required",
543 | "description": "*reserved*",
544 | "spec_title": "RFC7231#6.5.2",
545 | "spec_href": "http://tools.ietf.org/html/rfc7231#section-6.5.2"
546 | },
547 | "403": {
548 | "code": 403,
549 | "text": "Forbidden",
550 | "description": "\"The server understood the request but refuses to authorize it.\"",
551 | "spec_title": "RFC7231#6.5.3",
552 | "spec_href": "http://tools.ietf.org/html/rfc7231#section-6.5.3"
553 | },
554 | "404": {
555 | "code": 404,
556 | "text": "Not Found",
557 | "description": "\"The origin server did not find a current representation for the target resource or is not willing to disclose that one exists.\"",
558 | "spec_title": "RFC7231#6.5.4",
559 | "spec_href": "http://tools.ietf.org/html/rfc7231#section-6.5.4"
560 | },
561 | "405": {
562 | "code": 405,
563 | "text": "Method Not Allowed",
564 | "description": "\"The method specified in the request-line is known by the origin server but not supported by the target resource.\"",
565 | "spec_title": "RFC7231#6.5.5",
566 | "spec_href": "http://tools.ietf.org/html/rfc7231#section-6.5.5"
567 | },
568 | "406": {
569 | "code": 406,
570 | "text": "Not Acceptable",
571 | "description": "\"The target resource does not have a current representation that would be acceptable to the user agent, according to the proactive negotiation header fields received in the request, and the server is unwilling to supply a default representation.\"",
572 | "spec_title": "RFC7231#6.5.6",
573 | "spec_href": "http://tools.ietf.org/html/rfc7231#section-6.5.6"
574 | },
575 | "407": {
576 | "code": 407,
577 | "text": "Proxy Authentication Required",
578 | "description": "\"The client needs to authenticate itself in order to use a proxy.\"",
579 | "spec_title": "RFC7231#6.3.2",
580 | "spec_href": "http://tools.ietf.org/html/rfc7231#section-6.3.2"
581 | },
582 | "408": {
583 | "code": 408,
584 | "text": "Request Timeout",
585 | "description": "\"The server did not receive a complete request message within the time that it was prepared to wait.\"",
586 | "spec_title": "RFC7231#6.5.7",
587 | "spec_href": "http://tools.ietf.org/html/rfc7231#section-6.5.7"
588 | },
589 | "409": {
590 | "code": 409,
591 | "text": "Conflict",
592 | "description": "\"The request could not be completed due to a conflict with the current state of the resource.\"",
593 | "spec_title": "RFC7231#6.5.8",
594 | "spec_href": "http://tools.ietf.org/html/rfc7231#section-6.5.8"
595 | },
596 | "410": {
597 | "code": 410,
598 | "text": "Gone",
599 | "description": "\"Access to the target resource is no longer available at the origin server and that this condition is likely to be permanent.\"",
600 | "spec_title": "RFC7231#6.5.9",
601 | "spec_href": "http://tools.ietf.org/html/rfc7231#section-6.5.9"
602 | },
603 | "411": {
604 | "code": 411,
605 | "text": "Length Required",
606 | "description": "\"The server refuses to accept the request without a defined Content-Length.\"",
607 | "spec_title": "RFC7231#6.5.10",
608 | "spec_href": "http://tools.ietf.org/html/rfc7231#section-6.5.10"
609 | },
610 | "412": {
611 | "code": 412,
612 | "text": "Precondition Failed",
613 | "description": "\"One or more preconditions given in the request header fields evaluated to false when tested on the server.\"",
614 | "spec_title": "RFC7232#4.2",
615 | "spec_href": "http://tools.ietf.org/html/rfc7232#section-4.2"
616 | },
617 | "413": {
618 | "code": 413,
619 | "text": "Payload Too Large",
620 | "description": "\"The server is refusing to process a request because the request payload is larger than the server is willing or able to process.\"",
621 | "spec_title": "RFC7231#6.5.11",
622 | "spec_href": "http://tools.ietf.org/html/rfc7231#section-6.5.11"
623 | },
624 | "414": {
625 | "code": 414,
626 | "text": "URI Too Long",
627 | "description": "\"The server is refusing to service the request because the request-target is longer than the server is willing to interpret.\"",
628 | "spec_title": "RFC7231#6.5.12",
629 | "spec_href": "http://tools.ietf.org/html/rfc7231#section-6.5.12"
630 | },
631 | "415": {
632 | "code": 415,
633 | "text": "Unsupported Media Type",
634 | "description": "\"The origin server is refusing to service the request because the payload is in a format not supported by the target resource for this method.\"",
635 | "spec_title": "RFC7231#6.5.13",
636 | "spec_href": "http://tools.ietf.org/html/rfc7231#section-6.5.13"
637 | },
638 | "416": {
639 | "code": 416,
640 | "text": "Range Not Satisfiable",
641 | "description": "\"None of the ranges in the request's Range header field overlap the current extent of the selected resource or that the set of ranges requested has been rejected due to invalid ranges or an excessive request of small or overlapping ranges.\"",
642 | "spec_title": "RFC7233#4.4",
643 | "spec_href": "http://tools.ietf.org/html/rfc7233#section-4.4"
644 | },
645 | "417": {
646 | "code": 417,
647 | "text": "Expectation Failed",
648 | "description": "\"The expectation given in the request's Expect header field could not be met by at least one of the inbound servers.\"",
649 | "spec_title": "RFC7231#6.5.14",
650 | "spec_href": "http://tools.ietf.org/html/rfc7231#section-6.5.14"
651 | },
652 | "418": {
653 | "code": 418,
654 | "text": "I'm a teapot",
655 | "description": "\"1988 April Fools Joke. Returned by tea pots requested to brew coffee.\"",
656 | "spec_title": "RFC 2324",
657 | "spec_href": "https://tools.ietf.org/html/rfc2324"
658 | },
659 | "426": {
660 | "code": 426,
661 | "text": "Upgrade Required",
662 | "description": "\"The server refuses to perform the request using the current protocol but might be willing to do so after the client upgrades to a different protocol.\"",
663 | "spec_title": "RFC7231#6.5.15",
664 | "spec_href": "http://tools.ietf.org/html/rfc7231#section-6.5.15"
665 | },
666 | "500": {
667 | "code": 500,
668 | "text": "Internal Server Error",
669 | "description": "\"The server encountered an unexpected condition that prevented it from fulfilling the request.\"",
670 | "spec_title": "RFC7231#6.6.1",
671 | "spec_href": "http://tools.ietf.org/html/rfc7231#section-6.6.1"
672 | },
673 | "501": {
674 | "code": 501,
675 | "text": "Not Implemented",
676 | "description": "\"The server does not support the functionality required to fulfill the request.\"",
677 | "spec_title": "RFC7231#6.6.2",
678 | "spec_href": "http://tools.ietf.org/html/rfc7231#section-6.6.2"
679 | },
680 | "502": {
681 | "code": 502,
682 | "text": "Bad Gateway",
683 | "description": "\"The server, while acting as a gateway or proxy, received an invalid response from an inbound server it accessed while attempting to fulfill the request.\"",
684 | "spec_title": "RFC7231#6.6.3",
685 | "spec_href": "http://tools.ietf.org/html/rfc7231#section-6.6.3"
686 | },
687 | "503": {
688 | "code": 503,
689 | "text": "Service Unavailable",
690 | "description": "\"The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay.\"",
691 | "spec_title": "RFC7231#6.6.4",
692 | "spec_href": "http://tools.ietf.org/html/rfc7231#section-6.6.4"
693 | },
694 | "504": {
695 | "code": 504,
696 | "text": "Gateway Time-out",
697 | "description": "\"The server, while acting as a gateway or proxy, did not receive a timely response from an upstream server it needed to access in order to complete the request.\"",
698 | "spec_title": "RFC7231#6.6.5",
699 | "spec_href": "http://tools.ietf.org/html/rfc7231#section-6.6.5"
700 | },
701 | "505": {
702 | "code": 505,
703 | "text": "HTTP Version Not Supported",
704 | "description": "\"The server does not support, or refuses to support, the protocol version that was used in the request message.\"",
705 | "spec_title": "RFC7231#6.6.6",
706 | "spec_href": "http://tools.ietf.org/html/rfc7231#section-6.6.6"
707 | },
708 | "102": {
709 | "code": 102,
710 | "text": "Processing",
711 | "description": "\"An interim response to inform the client that the server has accepted the complete request, but has not yet completed it.\"",
712 | "spec_title": "RFC5218#10.1",
713 | "spec_href": "http://tools.ietf.org/html/rfc2518#section-10.1"
714 | },
715 | "207": {
716 | "code": 207,
717 | "text": "Multi-Status",
718 | "description": "\"Status for multiple independent operations.\"",
719 | "spec_title": "RFC5218#10.2",
720 | "spec_href": "http://tools.ietf.org/html/rfc2518#section-10.2"
721 | },
722 | "226": {
723 | "code": 226,
724 | "text": "IM Used",
725 | "description": "\"The server has fulfilled a GET request for the resource, and the response is a representation of the result of one or more instance-manipulations applied to the current instance.\"",
726 | "spec_title": "RFC3229#10.4.1",
727 | "spec_href": "http://tools.ietf.org/html/rfc3229#section-10.4.1"
728 | },
729 | "308": {
730 | "code": 308,
731 | "text": "Permanent Redirect",
732 | "description": "\"The target resource has been assigned a new permanent URI and any future references to this resource SHOULD use one of the returned URIs. [...] This status code is similar to 301 Moved Permanently (Section 7.3.2 of rfc7231), except that it does not allow rewriting the request method from POST to GET.\"",
733 | "spec_title": "RFC7238",
734 | "spec_href": "http://tools.ietf.org/html/rfc7238"
735 | },
736 | "422": {
737 | "code": 422,
738 | "text": "Unprocessable Entity",
739 | "description": "\"The server understands the content type of the request entity (hence a 415(Unsupported Media Type) status code is inappropriate), and the syntax of the request entity is correct (thus a 400 (Bad Request) status code is inappropriate) but was unable to process the contained instructions.\"",
740 | "spec_title": "RFC5218#10.3",
741 | "spec_href": "http://tools.ietf.org/html/rfc2518#section-10.3"
742 | },
743 | "423": {
744 | "code": 423,
745 | "text": "Locked",
746 | "description": "\"The source or destination resource of a method is locked.\"",
747 | "spec_title": "RFC5218#10.4",
748 | "spec_href": "http://tools.ietf.org/html/rfc2518#section-10.4"
749 | },
750 | "424": {
751 | "code": 424,
752 | "text": "Failed Dependency",
753 | "description": "\"The method could not be performed on the resource because the requested action depended on another action and that action failed.\"",
754 | "spec_title": "RFC5218#10.5",
755 | "spec_href": "http://tools.ietf.org/html/rfc2518#section-10.5"
756 | },
757 | "428": {
758 | "code": 428,
759 | "text": "Precondition Required",
760 | "description": "\"The origin server requires the request to be conditional.\"",
761 | "spec_title": "RFC6585#3",
762 | "spec_href": "http://tools.ietf.org/html/rfc6585#section-3"
763 | },
764 | "429": {
765 | "code": 429,
766 | "text": "Too Many Requests",
767 | "description": "\"The user has sent too many requests in a given amount of time (\"rate limiting\").\"",
768 | "spec_title": "RFC6585#4",
769 | "spec_href": "http://tools.ietf.org/html/rfc6585#section-4"
770 | },
771 | "431": {
772 | "code": 431,
773 | "text": "Request Header Fields Too Large",
774 | "description": "\"The server is unwilling to process the request because its header fields are too large.\"",
775 | "spec_title": "RFC6585#5",
776 | "spec_href": "http://tools.ietf.org/html/rfc6585#section-5"
777 | },
778 | "451": {
779 | "code": 451,
780 | "text": "Unavailable For Legal Reasons",
781 | "description": "\"The server is denying access to the resource in response to a legal demand.\"",
782 | "spec_title": "draft-ietf-httpbis-legally-restricted-status",
783 | "spec_href": "http://tools.ietf.org/html/draft-ietf-httpbis-legally-restricted-status"
784 | },
785 | "506": {
786 | "code": 506,
787 | "text": "Variant Also Negotiates",
788 | "description": "\"The server has an internal configuration error: the chosen variant resource is configured to engage in transparent content negotiation itself, and is therefore not a proper end point in the negotiation process.\"",
789 | "spec_title": "RFC2295#8.1",
790 | "spec_href": "http://tools.ietf.org/html/rfc2295#section-8.1"
791 | },
792 | "507": {
793 | "code": 507,
794 | "text": "Insufficient Storage",
795 | "description": "\The method could not be performed on the resource because the server is unable to store the representation needed to successfully complete the request.\"",
796 | "spec_title": "RFC5218#10.6",
797 | "spec_href": "http://tools.ietf.org/html/rfc2518#section-10.6"
798 | },
799 | "511": {
800 | "code": 511,
801 | "text": "Network Authentication Required",
802 | "description": "\"The client needs to authenticate to gain network access.\"",
803 | "spec_title": "RFC6585#6",
804 | "spec_href": "http://tools.ietf.org/html/rfc6585#section-6"
805 | }
806 | });
807 | }
808 | };
809 | });
810 |
811 | System.register("a2-in-memory-web-api/core", ["./in-memory-backend.service", "./http-status-codes"], function(exports_1, context_1) {
812 | "use strict";
813 | var __moduleName = context_1 && context_1.id;
814 | function exportStar_1(m) {
815 | var exports = {};
816 | for (var n in m) {
817 | if (n !== "default")
818 | exports[n] = m[n];
819 | }
820 | exports_1(exports);
821 | }
822 | return {
823 | setters: [function(in_memory_backend_service_1_1) {
824 | exportStar_1(in_memory_backend_service_1_1);
825 | }, function(http_status_codes_1_1) {
826 | exportStar_1(http_status_codes_1_1);
827 | }],
828 | execute: function() {}
829 | };
830 | });
831 |
--------------------------------------------------------------------------------
/http/styles.css:
--------------------------------------------------------------------------------
1 | /* Master Styles */
2 | h1 {
3 | color: #369;
4 | font-family: Arial, Helvetica, sans-serif;
5 | font-size: 250%;
6 | }
7 | h2, h3 {
8 | color: #444;
9 | font-family: Arial, Helvetica, sans-serif;
10 | font-weight: lighter;
11 | }
12 | body {
13 | margin: 2em;
14 | }
15 | body, input[text], button {
16 | color: #888;
17 | font-family: Cambria, Georgia;
18 | }
19 | a {
20 | cursor: pointer;
21 | cursor: hand;
22 | }
23 | button {
24 | font-family: Arial;
25 | background-color: #eee;
26 | border: none;
27 | padding: 5px 10px;
28 | border-radius: 4px;
29 | cursor: pointer;
30 | cursor: hand;
31 | }
32 | button:hover {
33 | background-color: #cfd8dc;
34 | }
35 | button:disabled {
36 | background-color: #eee;
37 | color: #aaa;
38 | cursor: auto;
39 | }
40 |
41 | /* Navigation link styles */
42 | nav a {
43 | padding: 5px 10px;
44 | text-decoration: none;
45 | margin-top: 10px;
46 | display: inline-block;
47 | background-color: #eee;
48 | border-radius: 4px;
49 | }
50 | nav a:visited, a:link {
51 | color: #607D8B;
52 | }
53 | nav a:hover {
54 | color: #039be5;
55 | background-color: #CFD8DC;
56 | }
57 | nav a.router-link-active {
58 | color: #039be5;
59 | }
60 |
61 | /* items class */
62 | .items {
63 | margin: 0 0 2em 0;
64 | list-style-type: none;
65 | padding: 0;
66 | width: 24em;
67 | }
68 | .items li {
69 | cursor: pointer;
70 | position: relative;
71 | left: 0;
72 | background-color: #EEE;
73 | margin: .5em;
74 | padding: .3em 0;
75 | height: 1.6em;
76 | border-radius: 4px;
77 | }
78 | .items li:hover {
79 | color: #607D8B;
80 | background-color: #DDD;
81 | left: .1em;
82 | }
83 | .items li.selected:hover {
84 | background-color: #BBD8DC;
85 | color: white;
86 | }
87 | .items .text {
88 | position: relative;
89 | top: -3px;
90 | }
91 | .items {
92 | margin: 0 0 2em 0;
93 | list-style-type: none;
94 | padding: 0;
95 | width: 24em;
96 | }
97 | .items li {
98 | cursor: pointer;
99 | position: relative;
100 | left: 0;
101 | background-color: #EEE;
102 | margin: .5em;
103 | padding: .3em 0;
104 | height: 1.6em;
105 | border-radius: 4px;
106 | }
107 | .items li:hover {
108 | color: #607D8B;
109 | background-color: #DDD;
110 | left: .1em;
111 | }
112 | .items li.selected {
113 | background-color: #CFD8DC;
114 | color: white;
115 | }
116 |
117 | .items li.selected:hover {
118 | background-color: #BBD8DC;
119 | }
120 | .items .text {
121 | position: relative;
122 | top: -3px;
123 | }
124 | .items .badge {
125 | display: inline-block;
126 | font-size: small;
127 | color: white;
128 | padding: 0.8em 0.7em 0 0.7em;
129 | background-color: #607D8B;
130 | line-height: 1em;
131 | position: relative;
132 | left: -1px;
133 | top: -4px;
134 | height: 1.8em;
135 | margin-right: .8em;
136 | border-radius: 4px 0 0 4px;
137 | }
138 |
139 | /* everywhere else */
140 | * {
141 | font-family: Arial, Helvetica, sans-serif;
142 | }
143 |
144 |
145 | /*
146 | Copyright 2016 Google Inc. All Rights Reserved.
147 | Use of this source code is governed by an MIT-style license that
148 | can be found in the LICENSE file at http://angular.io/license
149 | */
--------------------------------------------------------------------------------
/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | angular2-tutorial
6 |
7 |
8 | demo list
9 |
20 |
21 |
--------------------------------------------------------------------------------
/lifecycle/app/app.ts:
--------------------------------------------------------------------------------
1 | import {Component} from 'angular2/core';
2 | import {bootstrap} from 'angular2/platform/browser';
3 | import {UnlessDirective}from './unless.directive';
4 | import {Lifecycle} from './lifecycle'
5 |
6 | @Component({
7 | selector: "app",
8 | directives:[UnlessDirective,Lifecycle],
9 | template: `
10 |
16 |
17 |
18 | `
19 | })
20 | export class App {
21 | constructor() {}
22 | }
23 |
24 | bootstrap(App, [])
25 | .catch(err => console.error(err));
26 |
27 |
--------------------------------------------------------------------------------
/lifecycle/app/lifecycle.ts:
--------------------------------------------------------------------------------
1 | import {Component,Input} from 'angular2/core';
2 | import {bootstrap} from 'angular2/platform/browser';
3 | import {OnChanges, SimpleChange,OnInit,AfterContentInit,AfterContentChecked,AfterViewInit,AfterViewChecked,OnDestroy} from 'angular2/core';
4 |
5 | @Component({
6 | selector: "lifecycle",
7 | template: `
8 |
9 | {{name}}
10 |
11 |
12 | `
13 | })
14 | export class Lifecycle
15 | implements OnChanges, OnInit,AfterContentInit,AfterContentChecked,AfterViewInit, AfterViewChecked, OnDestroy{
16 | @Input()
17 | name:string
18 | doSomething(){
19 | console.log('***********doSomething**********');
20 | setTimeout(()=>{
21 | console.log('***********setTimeout**********');
22 | this.name='susan'
23 | },1000)
24 | }
25 | ngOnInit(){console.log('onInit');}
26 | ngOnDestroy(){console.log('OnDestroy')}
27 | ngOnChanges(changes: {[propertyName: string]: SimpleChange}){console.log('ngOnChanges',changes)}
28 | ngAfterContentInit(){console.log('AfterContentInit')}
29 | ngAfterContentChecked(){console.log('AfterContentChecked')}
30 | ngAfterViewInit(){console.log('AfterViewInit')}
31 | ngAfterViewChecked(){console.log('AfterViewChecked')}
32 | }
33 |
34 |
35 |
--------------------------------------------------------------------------------
/lifecycle/app/main.ts:
--------------------------------------------------------------------------------
1 | import {bootstrap} from 'angular2/platform/browser';
2 | import {App} from './app';
3 |
4 | bootstrap(App).catch(err => console.error(err));
5 |
6 | /*
7 | Copyright 2016 Google Inc. All Rights Reserved.
8 | Use of this source code is governed by an MIT-style license that
9 | can be found in the LICENSE file at http://angular.io/license
10 | */
--------------------------------------------------------------------------------
/lifecycle/app/unless.directive.ts:
--------------------------------------------------------------------------------
1 | import {Directive, Input} from 'angular2/core';
2 | import {TemplateRef, ViewContainerRef} from 'angular2/core';
3 | @Directive({ selector: '[myUnless]' })
4 | export class UnlessDirective {
5 | constructor(
6 | private _templateRef: TemplateRef,
7 | private _viewContainer: ViewContainerRef
8 | ) { }
9 | @Input() set myUnless(condition: boolean) {
10 | if (!condition) {
11 | this._viewContainer.createEmbeddedView(this._templateRef);
12 | } else {
13 | this._viewContainer.clear();
14 | }
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/lifecycle/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Angular 2 Demo
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
26 |
27 |
28 |
29 | Loading...
30 |
31 |
32 |
33 |
34 |
--------------------------------------------------------------------------------
/pipes/app/app.ts:
--------------------------------------------------------------------------------
1 | import {Component} from 'angular2/core';
2 | import {PowerBooster} from './stateless/power-booster.component';
3 | import {HeroListComponent} from './stateful/hero-list.component';
4 |
5 | @Component({
6 | selector: 'app',
7 | directives: [PowerBooster, HeroListComponent],
8 | template: `
9 |
10 |
11 |
12 | `
13 | })
14 | export class App {
15 | }
16 |
--------------------------------------------------------------------------------
/pipes/app/main.ts:
--------------------------------------------------------------------------------
1 | import {bootstrap} from 'angular2/platform/browser';
2 | import {App} from './app';
3 |
4 | bootstrap(App).catch(err => console.error(err));
5 |
6 | /*
7 | Copyright 2016 Google Inc. All Rights Reserved.
8 | Use of this source code is governed by an MIT-style license that
9 | can be found in the LICENSE file at http://angular.io/license
10 | */
--------------------------------------------------------------------------------
/pipes/app/stateful/fetch-json.pipe.ts:
--------------------------------------------------------------------------------
1 | declare var fetch;
2 | import {Pipe, PipeTransform} from 'angular2/core';
3 | @Pipe({
4 | name: 'fetch',
5 | pure: false
6 | })
7 | export class FetchJsonPipe implements PipeTransform {
8 | private fetchedValue: any;
9 | private fetchPromise: Promise;
10 | transform(value: string, args: string[]): any {
11 | if (!this.fetchPromise) {
12 | this.fetchPromise = fetch(value)
13 | .then((result: any) => result.json())
14 | .then((json: any) => this.fetchedValue = json);
15 | }
16 | return this.fetchedValue;
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/pipes/app/stateful/hero-list.component.ts:
--------------------------------------------------------------------------------
1 | import {Component} from 'angular2/core';
2 | import {FetchJsonPipe} from './fetch-json.pipe';
3 | @Component({
4 | selector: 'hero-list',
5 | template: `
6 | Heroes from JSON File
7 |
8 | {{hero.name}}
9 |
10 | Heroes as JSON:
11 | {{'heroes.json' | fetch | json}}
12 |
13 | `,
14 | pipes: [FetchJsonPipe]
15 | })
16 | export class HeroListComponent {
17 | /* I've got nothing to do ;-) */
18 | }
19 |
--------------------------------------------------------------------------------
/pipes/app/stateless/exponential-strength.pipe.ts:
--------------------------------------------------------------------------------
1 | import {Pipe, PipeTransform} from 'angular2/core';
2 | /*
3 | * Raise the value exponentially
4 | * Takes an exponent argument that defaults to 1.
5 | * Usage:
6 | * value | exponentialStrength:exponent
7 | * Example:
8 | * {{ 2 | exponentialStrength:10}}
9 | * formats to: 1024
10 | */
11 | @Pipe({name: 'exponentialStrength'})
12 | export class ExponentialStrengthPipe implements PipeTransform {
13 | transform(value: number, args: string[]) : any {
14 | return Math.pow(value, parseInt(args[0] || '1', 10));
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/pipes/app/stateless/power-booster.component.ts:
--------------------------------------------------------------------------------
1 | import {Component} from 'angular2/core';
2 | import {ExponentialStrengthPipe} from './exponential-strength.pipe';
3 | @Component({
4 | selector: 'power-booster',
5 | template: `
6 | Power Booster
7 |
8 | Super power boost: {{2 | exponentialStrength: 10}}
9 |
10 | `,
11 | pipes: [ExponentialStrengthPipe]
12 | })
13 | export class PowerBooster { }
14 |
--------------------------------------------------------------------------------
/pipes/heroes.json:
--------------------------------------------------------------------------------
1 | [{"name":"lewis"},{"name":"susan"},{"name":"lisa"}]
--------------------------------------------------------------------------------
/pipes/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Angular 2 Demo
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
26 |
27 |
28 |
29 | Loading...
30 |
31 |
32 |
33 |
34 |
--------------------------------------------------------------------------------
/router/app/app.component.ts:
--------------------------------------------------------------------------------
1 | import {Component} from 'angular2/core';
2 | import {RouteConfig, ROUTER_DIRECTIVES} from 'angular2/router';
3 |
4 | import {CrisisCenterComponent} from './crisis-center/crisis-center.component';
5 | import {HeroListComponent} from './heroes/hero-list.component';
6 | import {HeroDetailComponent} from './heroes/hero-detail.component';
7 |
8 | import {DialogService} from './dialog.service';
9 | import {HeroService} from './heroes/hero.service';
10 |
11 | @Component({
12 | selector: 'my-app',
13 | template: `
14 | Component Router
15 |
19 |
20 | `,
21 | providers: [DialogService, HeroService],
22 | directives: [ROUTER_DIRECTIVES]
23 | })
24 | @RouteConfig([
25 |
26 | { // Crisis Center child route
27 | path: '/crisis-center/...',
28 | name: 'CrisisCenter',
29 | component: CrisisCenterComponent,
30 | useAsDefault: true
31 | },
32 |
33 | {path: '/heroes', name: 'Heroes', component: HeroListComponent},
34 | {path: '/hero/:id', name: 'HeroDetail', component: HeroDetailComponent},
35 | {path: '/disaster', name: 'Asteroid', redirectTo: ['CrisisCenter', 'CrisisDetail', {id:3}]}
36 | ])
37 | export class AppComponent { }
38 |
39 |
40 | /*
41 | Copyright 2016 Google Inc. All Rights Reserved.
42 | Use of this source code is governed by an MIT-style license that
43 | can be found in the LICENSE file at http://angular.io/license
44 | */
--------------------------------------------------------------------------------
/router/app/crisis-center/crisis-center.component.ts:
--------------------------------------------------------------------------------
1 | import {Component} from 'angular2/core';
2 | import {RouteConfig, RouterOutlet} from 'angular2/router';
3 |
4 | import {CrisisListComponent} from './crisis-list.component';
5 | import {CrisisDetailComponent} from './crisis-detail.component';
6 | import {CrisisService} from './crisis.service';
7 |
8 | @Component({
9 | template: `
10 | CRISIS CENTER
11 |
12 | `,
13 | directives: [RouterOutlet],
14 | providers: [CrisisService]
15 | })
16 | @RouteConfig([
17 | {path:'/', name: 'CrisisList', component: CrisisListComponent, useAsDefault: true},
18 | {path:'/:id', name: 'CrisisDetail', component: CrisisDetailComponent}
19 | ])
20 | export class CrisisCenterComponent { }
21 |
22 |
23 | /*
24 | Copyright 2016 Google Inc. All Rights Reserved.
25 | Use of this source code is governed by an MIT-style license that
26 | can be found in the LICENSE file at http://angular.io/license
27 | */
--------------------------------------------------------------------------------
/router/app/crisis-center/crisis-detail.component.ts:
--------------------------------------------------------------------------------
1 |
2 | import {Component, OnInit} from 'angular2/core';
3 | import {Crisis, CrisisService} from './crisis.service';
4 | import {RouteParams, Router} from 'angular2/router';
5 | import {CanDeactivate, ComponentInstruction} from 'angular2/router';
6 | import {DialogService} from '../dialog.service';
7 |
8 | @Component({
9 | template: `
10 |
11 |
"{{editName}}"
12 |
13 | {{crisis.id}}
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 | `,
24 | styles: ['input {width: 20em}']
25 | })
26 |
27 | export class CrisisDetailComponent implements OnInit, CanDeactivate {
28 |
29 | crisis: Crisis;
30 | editName: string;
31 |
32 | constructor(
33 | private _service: CrisisService,
34 | private _router: Router,
35 | private _routeParams: RouteParams,
36 | private _dialog: DialogService
37 | ) { }
38 |
39 | ngOnInit() {
40 | let id = +this._routeParams.get('id');
41 | this._service.getCrisis(id).then(crisis => {
42 | if (crisis) {
43 | this.editName = crisis.name;
44 | this.crisis = crisis;
45 | } else { // id not found
46 | this.gotoCrises();
47 | }
48 | });
49 | }
50 |
51 | routerCanDeactivate(next: ComponentInstruction, prev: ComponentInstruction) : any {
52 | // Allow synchronous navigation (`true`) if no crisis or the crisis is unchanged.
53 | if (!this.crisis || this.crisis.name === this.editName) {
54 | return true;
55 | }
56 | // Otherwise ask the user with the dialog service and return its
57 | // promise which resolves to true or false when the user decides
58 | return this._dialog.confirm('Discard changes?');
59 | }
60 |
61 | cancel() {
62 | this.editName = this.crisis.name;
63 | this.gotoCrises();
64 | }
65 |
66 | save() {
67 | this.crisis.name = this.editName;
68 | this.gotoCrises();
69 | }
70 |
71 | gotoCrises() {
72 | let crisisId = this.crisis ? this.crisis.id : null;
73 | // Pass along the hero id if available
74 | // so that the CrisisListComponent can select that hero.
75 | // Add a totally useless `foo` parameter for kicks.
76 | this._router.navigate(['CrisisList', {id: crisisId, foo: 'foo'} ]);
77 | }
78 | }
79 |
80 |
81 | /*
82 | Copyright 2016 Google Inc. All Rights Reserved.
83 | Use of this source code is governed by an MIT-style license that
84 | can be found in the LICENSE file at http://angular.io/license
85 | */
--------------------------------------------------------------------------------
/router/app/crisis-center/crisis-list.component.ts:
--------------------------------------------------------------------------------
1 |
2 | import {Component, OnInit} from 'angular2/core';
3 | import {Crisis, CrisisService} from './crisis.service';
4 | import {Router, RouteParams} from 'angular2/router';
5 |
6 | @Component({
7 | template: `
8 |
9 | -
12 | {{crisis.id}} {{crisis.name}}
13 |
14 |
15 | `,
16 | })
17 | export class CrisisListComponent implements OnInit {
18 | crises: Crisis[];
19 |
20 | private _selectedId: number;
21 |
22 | constructor(
23 | private _service: CrisisService,
24 | private _router: Router,
25 | routeParams: RouteParams) {
26 | this._selectedId = +routeParams.get('id');
27 | }
28 |
29 | isSelected(crisis: Crisis) { return crisis.id === this._selectedId; }
30 |
31 | ngOnInit() {
32 | this._service.getCrises().then(crises => this.crises = crises);
33 | }
34 |
35 | onSelect(crisis: Crisis) {
36 | this._router.navigate( ['CrisisDetail', { id: crisis.id }] );
37 | }
38 | }
39 |
40 |
41 | /*
42 | Copyright 2016 Google Inc. All Rights Reserved.
43 | Use of this source code is governed by an MIT-style license that
44 | can be found in the LICENSE file at http://angular.io/license
45 | */
--------------------------------------------------------------------------------
/router/app/crisis-center/crisis.service.ts:
--------------------------------------------------------------------------------
1 |
2 | import {Injectable} from 'angular2/core';
3 |
4 | export class Crisis {
5 | constructor(public id: number, public name: string) { }
6 | }
7 |
8 | @Injectable()
9 | export class CrisisService {
10 | getCrises() { return crisesPromise; }
11 |
12 | getCrisis(id: number | string) {
13 | return crisesPromise
14 | .then(crises => crises.filter(c => c.id === +id)[0]);
15 | }
16 |
17 |
18 | static nextCrisisId = 100;
19 |
20 | addCrisis(name:string) {
21 | name = name.trim();
22 | if (name){
23 | let crisis = new Crisis(CrisisService.nextCrisisId++, name);
24 | crisesPromise.then(crises => crises.push(crisis));
25 | }
26 | }
27 | }
28 |
29 | var crises = [
30 | new Crisis(1, 'Dragon Burning Cities'),
31 | new Crisis(2, 'Sky Rains Great White Sharks'),
32 | new Crisis(3, 'Giant Asteroid Heading For Earth'),
33 | new Crisis(4, 'Procrastinators Meeting Delayed Again'),
34 | ];
35 |
36 | var crisesPromise = Promise.resolve(crises);
37 |
38 |
39 | /*
40 | Copyright 2016 Google Inc. All Rights Reserved.
41 | Use of this source code is governed by an MIT-style license that
42 | can be found in the LICENSE file at http://angular.io/license
43 | */
--------------------------------------------------------------------------------
/router/app/dialog.service.ts:
--------------------------------------------------------------------------------
1 | import {Injectable} from 'angular2/core';
2 | /**
3 | * Async modal dialog service
4 | * DialogService makes this app easier to test by faking this service.
5 | * TODO: better modal implemenation that doesn't use window.confirm
6 | */
7 | @Injectable()
8 | export class DialogService {
9 | /**
10 | * Ask user to confirm an action. `message` explains the action and choices.
11 | * Returns promise resolving to `true`=confirm or `false`=cancel
12 | */
13 | confirm(message?:string) {
14 | return new Promise((resolve, reject) =>
15 | resolve(window.confirm(message || 'Is it OK?')));
16 | };
17 | }
18 |
19 |
20 | /*
21 | Copyright 2016 Google Inc. All Rights Reserved.
22 | Use of this source code is governed by an MIT-style license that
23 | can be found in the LICENSE file at http://angular.io/license
24 | */
--------------------------------------------------------------------------------
/router/app/heroes/hero-detail.component.ts:
--------------------------------------------------------------------------------
1 | import {Component, OnInit} from 'angular2/core';
2 | import {Hero, HeroService} from './hero.service';
3 | import {RouteParams, Router} from 'angular2/router';
4 |
5 | @Component({
6 | template: `
7 | HEROES
8 |
9 |
"{{hero.name}}"
10 |
11 | {{hero.id}}
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 | `,
21 | })
22 | export class HeroDetailComponent implements OnInit {
23 | hero: Hero;
24 |
25 | constructor(
26 | private _router:Router,
27 | private _routeParams:RouteParams,
28 | private _service:HeroService){}
29 |
30 | ngOnInit() {
31 | let id = this._routeParams.get('id');
32 | this._service.getHero(id).then(hero => this.hero = hero);
33 | }
34 |
35 | gotoHeroes() {
36 | let heroId = this.hero ? this.hero.id : null;
37 | // Pass along the hero id if available
38 | // so that the HeroList component can select that hero.
39 | // Add a totally useless `foo` parameter for kicks.
40 | this._router.navigate(['Heroes', {id: heroId, foo: 'foo'} ]);
41 | }
42 | }
43 |
44 |
45 | /*
46 | Copyright 2016 Google Inc. All Rights Reserved.
47 | Use of this source code is governed by an MIT-style license that
48 | can be found in the LICENSE file at http://angular.io/license
49 | */
--------------------------------------------------------------------------------
/router/app/heroes/hero-list.component.ts:
--------------------------------------------------------------------------------
1 |
2 | // TODO SOMEDAY: Feature Componetized like CrisisCenter
3 | import {Component, OnInit} from 'angular2/core';
4 | import {Hero, HeroService} from './hero.service';
5 | import {Router, RouteParams} from 'angular2/router';
6 |
7 | @Component({
8 | template: `
9 | HEROES
10 |
11 | -
14 | {{hero.id}} {{hero.name}}
15 |
16 |
17 | `
18 | })
19 | export class HeroListComponent implements OnInit {
20 | heroes: Hero[];
21 |
22 | private _selectedId: number;
23 |
24 | constructor(
25 | private _service: HeroService,
26 | private _router: Router,
27 | routeParams: RouteParams) {
28 | this._selectedId = +routeParams.get('id');
29 | }
30 |
31 | isSelected(hero: Hero) { return hero.id === this._selectedId; }
32 |
33 | onSelect(hero: Hero) {
34 | this._router.navigate( ['HeroDetail', { id: hero.id }] );
35 | }
36 |
37 | ngOnInit() {
38 | this._service.getHeroes().then(heroes => this.heroes = heroes)
39 | }
40 | }
41 |
42 |
43 | /*
44 | Copyright 2016 Google Inc. All Rights Reserved.
45 | Use of this source code is governed by an MIT-style license that
46 | can be found in the LICENSE file at http://angular.io/license
47 | */
--------------------------------------------------------------------------------
/router/app/heroes/hero.service.ts:
--------------------------------------------------------------------------------
1 | import {Injectable} from 'angular2/core';
2 |
3 | export class Hero {
4 | constructor(public id: number, public name: string) { }
5 | }
6 |
7 | @Injectable()
8 | export class HeroService {
9 | getHeroes() { return heroesPromise; }
10 |
11 | getHero(id: number | string) {
12 | return heroesPromise
13 | .then(heroes => heroes.filter(h => h.id === +id)[0]);
14 | }
15 | }
16 |
17 | var HEROES = [
18 | new Hero(11, 'Mr. Nice'),
19 | new Hero(12, 'Narco'),
20 | new Hero(13, 'Bombasto'),
21 | new Hero(14, 'Celeritas'),
22 | new Hero(15, 'Magneta'),
23 | new Hero(16, 'RubberMan')
24 | ];
25 |
26 | var heroesPromise = Promise.resolve(HEROES);
27 |
28 |
29 | /*
30 | Copyright 2016 Google Inc. All Rights Reserved.
31 | Use of this source code is governed by an MIT-style license that
32 | can be found in the LICENSE file at http://angular.io/license
33 | */
--------------------------------------------------------------------------------
/router/app/main.ts:
--------------------------------------------------------------------------------
1 | import {bootstrap} from 'angular2/platform/browser';
2 | import {ROUTER_PROVIDERS} from 'angular2/router';
3 |
4 | import {AppComponent} from './app.component';
5 |
6 | // Add these symbols to override the `LocationStrategy`
7 | //import {provide} from 'angular2/core';
8 | //import {LocationStrategy,
9 | // HashLocationStrategy} from 'angular2/router';
10 |
11 | bootstrap(AppComponent, [ROUTER_PROVIDERS,
12 | //provide(LocationStrategy,
13 | // {useClass: HashLocationStrategy}) // .../#/crisis-center/
14 | ]);
15 |
16 |
17 | /*
18 | Copyright 2016 Google Inc. All Rights Reserved.
19 | Use of this source code is governed by an MIT-style license that
20 | can be found in the LICENSE file at http://angular.io/license
21 | */
--------------------------------------------------------------------------------
/router/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 | Router Sample
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
34 |
35 |
36 |
37 | loading...
38 |
39 |
40 |
41 |
42 |
43 |
--------------------------------------------------------------------------------
/router/styles.css:
--------------------------------------------------------------------------------
1 | /* Master Styles */
2 | h1 {
3 | color: #369;
4 | font-family: Arial, Helvetica, sans-serif;
5 | font-size: 250%;
6 | }
7 | h2, h3 {
8 | color: #444;
9 | font-family: Arial, Helvetica, sans-serif;
10 | font-weight: lighter;
11 | }
12 | body {
13 | margin: 2em;
14 | }
15 | body, input[text], button {
16 | color: #888;
17 | font-family: Cambria, Georgia;
18 | }
19 | a {
20 | cursor: pointer;
21 | cursor: hand;
22 | }
23 | button {
24 | font-family: Arial;
25 | background-color: #eee;
26 | border: none;
27 | padding: 5px 10px;
28 | border-radius: 4px;
29 | cursor: pointer;
30 | cursor: hand;
31 | }
32 | button:hover {
33 | background-color: #cfd8dc;
34 | }
35 | button:disabled {
36 | background-color: #eee;
37 | color: #aaa;
38 | cursor: auto;
39 | }
40 |
41 | /* Navigation link styles */
42 | nav a {
43 | padding: 5px 10px;
44 | text-decoration: none;
45 | margin-top: 10px;
46 | display: inline-block;
47 | background-color: #eee;
48 | border-radius: 4px;
49 | }
50 | nav a:visited, a:link {
51 | color: #607D8B;
52 | }
53 | nav a:hover {
54 | color: #039be5;
55 | background-color: #CFD8DC;
56 | }
57 | nav a.router-link-active {
58 | color: #039be5;
59 | }
60 |
61 | /* items class */
62 | .items {
63 | margin: 0 0 2em 0;
64 | list-style-type: none;
65 | padding: 0;
66 | width: 24em;
67 | }
68 | .items li {
69 | cursor: pointer;
70 | position: relative;
71 | left: 0;
72 | background-color: #EEE;
73 | margin: .5em;
74 | padding: .3em 0;
75 | height: 1.6em;
76 | border-radius: 4px;
77 | }
78 | .items li:hover {
79 | color: #607D8B;
80 | background-color: #DDD;
81 | left: .1em;
82 | }
83 | .items li.selected:hover {
84 | background-color: #BBD8DC;
85 | color: white;
86 | }
87 | .items .text {
88 | position: relative;
89 | top: -3px;
90 | }
91 | .items {
92 | margin: 0 0 2em 0;
93 | list-style-type: none;
94 | padding: 0;
95 | width: 24em;
96 | }
97 | .items li {
98 | cursor: pointer;
99 | position: relative;
100 | left: 0;
101 | background-color: #EEE;
102 | margin: .5em;
103 | padding: .3em 0;
104 | height: 1.6em;
105 | border-radius: 4px;
106 | }
107 | .items li:hover {
108 | color: #607D8B;
109 | background-color: #DDD;
110 | left: .1em;
111 | }
112 | .items li.selected {
113 | background-color: #CFD8DC;
114 | color: white;
115 | }
116 |
117 | .items li.selected:hover {
118 | background-color: #BBD8DC;
119 | }
120 | .items .text {
121 | position: relative;
122 | top: -3px;
123 | }
124 | .items .badge {
125 | display: inline-block;
126 | font-size: small;
127 | color: white;
128 | padding: 0.8em 0.7em 0 0.7em;
129 | background-color: #607D8B;
130 | line-height: 1em;
131 | position: relative;
132 | left: -1px;
133 | top: -4px;
134 | height: 1.8em;
135 | margin-right: .8em;
136 | border-radius: 4px 0 0 4px;
137 | }
138 |
139 | /* everywhere else */
140 | * {
141 | font-family: Arial, Helvetica, sans-serif;
142 | }
143 |
144 |
145 | /*
146 | Copyright 2016 Google Inc. All Rights Reserved.
147 | Use of this source code is governed by an MIT-style license that
148 | can be found in the LICENSE file at http://angular.io/license
149 | */
--------------------------------------------------------------------------------
/service/app/app.component.ts:
--------------------------------------------------------------------------------
1 | import {Component, OnInit} from 'angular2/core';
2 | import {Hero} from './hero';
3 | import {HeroDetailComponent} from './hero-detail.component';
4 | import {HeroService} from './hero.service';
5 |
6 | @Component({
7 | selector: 'my-app',
8 | template: `
9 | {{title}}
10 | My Heroes
11 |
12 | -
15 | {{hero.id}} {{hero.name}}
16 |
17 |
18 |
19 | `,
20 | styles: [`
21 | .selected {
22 | background-color: #CFD8DC !important;
23 | color: white;
24 | }
25 | .heroes {
26 | margin: 0 0 2em 0;
27 | list-style-type: none;
28 | padding: 0;
29 | width: 10em;
30 | }
31 | .heroes li {
32 | cursor: pointer;
33 | position: relative;
34 | left: 0;
35 | background-color: #EEE;
36 | margin: .5em;
37 | padding: .3em 0em;
38 | height: 1.6em;
39 | border-radius: 4px;
40 | }
41 | .heroes li.selected:hover {
42 | color: white;
43 | }
44 | .heroes li:hover {
45 | color: #607D8B;
46 | background-color: #EEE;
47 | left: .1em;
48 | }
49 | .heroes .text {
50 | position: relative;
51 | top: -3px;
52 | }
53 | .heroes .badge {
54 | display: inline-block;
55 | font-size: small;
56 | color: white;
57 | padding: 0.8em 0.7em 0em 0.7em;
58 | background-color: #607D8B;
59 | line-height: 1em;
60 | position: relative;
61 | left: -1px;
62 | top: -4px;
63 | height: 1.8em;
64 | margin-right: .8em;
65 | border-radius: 4px 0px 0px 4px;
66 | }
67 | `],
68 | directives: [HeroDetailComponent],
69 | providers: [HeroService]
70 | })
71 | export class AppComponent implements OnInit {
72 | title = 'Tour of Heroes';
73 | heroes: Hero[];
74 | selectedHero: Hero;
75 |
76 | constructor(private _heroService: HeroService) { }
77 |
78 | getHeroes() {
79 | this._heroService.getHeroes().then(heroes => this.heroes = heroes);
80 | }
81 |
82 | ngOnInit() {
83 | this.getHeroes();
84 | }
85 |
86 | onSelect(hero: Hero) { this.selectedHero = hero; }
87 | }
88 |
89 |
90 | /*
91 | Copyright 2016 Google Inc. All Rights Reserved.
92 | Use of this source code is governed by an MIT-style license that
93 | can be found in the LICENSE file at http://angular.io/license
94 | */
95 |
--------------------------------------------------------------------------------
/service/app/app.ts:
--------------------------------------------------------------------------------
1 | import {Component} from 'angular2/core';
2 | import {AppComponent} from './app.component';
3 |
4 | @Component({
5 | selector: 'app',
6 | directives: [AppComponent],
7 | template: `
8 |
9 | `
10 | })
11 | export class App {
12 | }
13 |
--------------------------------------------------------------------------------
/service/app/hero-detail.component.ts:
--------------------------------------------------------------------------------
1 | import {Component} from 'angular2/core';
2 | import {Hero} from './hero';
3 |
4 | @Component({
5 | selector: 'my-hero-detail',
6 | template: `
7 |
8 |
{{hero.name}} details
9 |
10 | {{hero.id}}
11 |
12 |
13 |
14 |
15 |
16 |
17 | `,
18 | inputs: ['hero']
19 | })
20 | export class HeroDetailComponent {
21 | hero: Hero;
22 | }
23 |
24 |
25 | /*
26 | Copyright 2016 Google Inc. All Rights Reserved.
27 | Use of this source code is governed by an MIT-style license that
28 | can be found in the LICENSE file at http://angular.io/license
29 | */
30 |
--------------------------------------------------------------------------------
/service/app/hero.service.ts:
--------------------------------------------------------------------------------
1 | import {Hero} from './hero';
2 | import {HEROES} from './mock-heroes';
3 | import {Injectable} from 'angular2/core';
4 |
5 | @Injectable()
6 | export class HeroService {
7 | getHeroes() {
8 | return Promise.resolve(HEROES);
9 | }
10 | // See the "Take it slow" appendix
11 | getHeroesSlowly() {
12 | return new Promise(resolve =>
13 | setTimeout(() => resolve(HEROES), 2000) // 2 seconds
14 | );
15 | }
16 | }
17 |
18 | /*
19 | Copyright 2016 Google Inc. All Rights Reserved.
20 | Use of this source code is governed by an MIT-style license that
21 | can be found in the LICENSE file at http://angular.io/license
22 | */
23 |
--------------------------------------------------------------------------------
/service/app/hero.ts:
--------------------------------------------------------------------------------
1 | export interface Hero {
2 | id: number;
3 | name: string;
4 | }
5 |
6 |
7 | /*
8 | Copyright 2016 Google Inc. All Rights Reserved.
9 | Use of this source code is governed by an MIT-style license that
10 | can be found in the LICENSE file at http://angular.io/license
11 | */
--------------------------------------------------------------------------------
/service/app/main.ts:
--------------------------------------------------------------------------------
1 | import {bootstrap} from 'angular2/platform/browser';
2 | import {App} from './app';
3 |
4 | bootstrap(App).catch(err => console.error(err));
5 |
6 | /*
7 | Copyright 2016 Google Inc. All Rights Reserved.
8 | Use of this source code is governed by an MIT-style license that
9 | can be found in the LICENSE file at http://angular.io/license
10 | */
--------------------------------------------------------------------------------
/service/app/mock-heroes.ts:
--------------------------------------------------------------------------------
1 | import {Hero} from './hero';
2 |
3 | export var HEROES: Hero[] = [
4 | {'id': 11, 'name': 'Mr. Nice'},
5 | {'id': 12, 'name': 'Narco'},
6 | {'id': 13, 'name': 'Bombasto'},
7 | {'id': 14, 'name': 'Celeritas'},
8 | {'id': 15, 'name': 'Magneta'},
9 | {'id': 16, 'name': 'RubberMan'},
10 | {'id': 17, 'name': 'Dynama'},
11 | {'id': 18, 'name': 'Dr IQ'},
12 | {'id': 19, 'name': 'Magma'},
13 | {'id': 20, 'name': 'Tornado'}
14 | ];
15 |
16 | /*
17 | Copyright 2016 Google Inc. All Rights Reserved.
18 | Use of this source code is governed by an MIT-style license that
19 | can be found in the LICENSE file at http://angular.io/license
20 | */
21 |
--------------------------------------------------------------------------------
/service/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Angular 2 Demo
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
26 |
27 |
28 |
29 | Loading...
30 |
31 |
32 |
33 |
34 |
--------------------------------------------------------------------------------
/template-syntax/app/app.ts:
--------------------------------------------------------------------------------
1 | import {Component} from 'angular2/core';
2 |
3 | @Component({
4 | selector: 'app',
5 | template: `
6 |
7 |
属性绑定
8 |
9 |
10 |
11 |
事件
12 |
13 |
14 |
双向数据绑定
15 |
16 |
17 |
18 |
#局部变量
19 |
20 |
21 |
22 |
23 |
24 |
25 |
*语法
26 |
我是段落
27 |
我是段落
28 |
29 |
`
30 | })
31 | export class App {
32 | firstName:string = 'lewis';
33 |
34 | doSomething($event) {
35 | console.log('点击了这个按钮:', $event.target);
36 | }
37 |
38 | callPhone(val) {
39 | console.log('局部变量phone的值:', val);
40 | }
41 |
42 | callFax(val) {
43 | console.log('局部变量fax的值:', val);
44 | }
45 |
46 | isActive:boolean = true;
47 | }
--------------------------------------------------------------------------------
/template-syntax/app/main.ts:
--------------------------------------------------------------------------------
1 | import {bootstrap} from 'angular2/platform/browser';
2 | import {App} from './app';
3 |
4 | bootstrap(App).catch(err => console.error(err));
5 |
6 | /*
7 | Copyright 2016 Google Inc. All Rights Reserved.
8 | Use of this source code is governed by an MIT-style license that
9 | can be found in the LICENSE file at http://angular.io/license
10 | */
--------------------------------------------------------------------------------
/template-syntax/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Angular 2 Demo
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
26 |
27 |
28 |
29 | Loading...
30 |
31 |
32 |
33 |
34 |
--------------------------------------------------------------------------------