From bd079369f390c83b319d966fcfda158296d9cc1a Mon Sep 17 00:00:00 2001 From: John Papa Date: Fri, 1 Apr 2016 17:23:34 -0700 Subject: [PATCH 1/5] docs(style-guide): add A2 styleguide - v1 --- .../style-guide/ts/001/app/app.component.ts | 29 + .../style-guide/ts/001/app/hero.model.ts | 9 + .../style-guide/ts/001/app/hero.service.ts | 14 + .../_examples/style-guide/ts/001/app/main.ts | 9 + .../style-guide/ts/001/app/placeholder.ts | 93 +++ .../ts/example-config.json | 0 .../{router => style-guide}/ts/index.html | 2 +- .../docs/_examples/style-guide/ts/plnkr.json | 8 + public/docs/dart/latest/guide/_data.json | 8 +- .../docs/dart/latest/guide/style-guide.jade | 1 + public/docs/js/latest/guide/_data.json | 8 +- public/docs/js/latest/guide/style-guide.jade | 1 + public/docs/ts/latest/guide/_data.json | 6 + public/docs/ts/latest/guide/style-guide.jade | 665 ++++++++++++++++++ 14 files changed, 850 insertions(+), 3 deletions(-) create mode 100644 public/docs/_examples/style-guide/ts/001/app/app.component.ts create mode 100644 public/docs/_examples/style-guide/ts/001/app/hero.model.ts create mode 100644 public/docs/_examples/style-guide/ts/001/app/hero.service.ts create mode 100644 public/docs/_examples/style-guide/ts/001/app/main.ts create mode 100644 public/docs/_examples/style-guide/ts/001/app/placeholder.ts rename public/docs/_examples/{router => style-guide}/ts/example-config.json (100%) rename public/docs/_examples/{router => style-guide}/ts/index.html (97%) create mode 100644 public/docs/_examples/style-guide/ts/plnkr.json create mode 100644 public/docs/dart/latest/guide/style-guide.jade create mode 100644 public/docs/js/latest/guide/style-guide.jade create mode 100644 public/docs/ts/latest/guide/style-guide.jade diff --git a/public/docs/_examples/style-guide/ts/001/app/app.component.ts b/public/docs/_examples/style-guide/ts/001/app/app.component.ts new file mode 100644 index 0000000000..885ef3a0e6 --- /dev/null +++ b/public/docs/_examples/style-guide/ts/001/app/app.component.ts @@ -0,0 +1,29 @@ +// #docplaster + +// #docregion +/* recommended */ + +// app.component.ts +import { Component, OnInit } from 'angular2/core'; + +import { Hero } from './hero'; +import { HeroService } from './hero.service'; + +@Component({ + selector: 'my-app', + template: ` +
{{heroes | json}}
+ `, + styleUrls: ['app/app.component.css'], + providers: [HeroService] +}) +export class AppComponent implements OnInit{ + heroes: Hero[] = []; + + constructor(private _heroService: HeroService) {} + + ngOnInit() { + this._heroService.getHeroes() + .then(heroes => this.heroes = heroes); + } +} diff --git a/public/docs/_examples/style-guide/ts/001/app/hero.model.ts b/public/docs/_examples/style-guide/ts/001/app/hero.model.ts new file mode 100644 index 0000000000..5246ac4f1c --- /dev/null +++ b/public/docs/_examples/style-guide/ts/001/app/hero.model.ts @@ -0,0 +1,9 @@ +// #docplaster + +// #docregion +/* recommended */ + +export class Hero { + id: number; + name: string; +} diff --git a/public/docs/_examples/style-guide/ts/001/app/hero.service.ts b/public/docs/_examples/style-guide/ts/001/app/hero.service.ts new file mode 100644 index 0000000000..937b543e7e --- /dev/null +++ b/public/docs/_examples/style-guide/ts/001/app/hero.service.ts @@ -0,0 +1,14 @@ +// #docplaster + +// #docregion +/* recommended */ + +import { Injectable } from 'angular2/core'; +import { HEROES } from './mock-heroes'; + +@Injectable() +export class HeroService { + getHeroes() { + return Promise.resolve(HEROES); + } +} diff --git a/public/docs/_examples/style-guide/ts/001/app/main.ts b/public/docs/_examples/style-guide/ts/001/app/main.ts new file mode 100644 index 0000000000..90f0596ef0 --- /dev/null +++ b/public/docs/_examples/style-guide/ts/001/app/main.ts @@ -0,0 +1,9 @@ +// #docplaster + +// #docregion +/* recommended */ + +import { bootstrap } from 'angular2/platform/browser'; +import { AppComponent } from './app.component'; + +bootstrap(AppComponent, []); diff --git a/public/docs/_examples/style-guide/ts/001/app/placeholder.ts b/public/docs/_examples/style-guide/ts/001/app/placeholder.ts new file mode 100644 index 0000000000..9c78c378ce --- /dev/null +++ b/public/docs/_examples/style-guide/ts/001/app/placeholder.ts @@ -0,0 +1,93 @@ +// #docplaster + +// #docregion 001-1 + /* avoid */ + import { bootstrap } from 'angular2/platform/browser'; + import { Component, OnInit } from 'angular2/core'; + + @Component({ + selector: 'my-app', + template: ` +

{{title}}

+
{{heroes | json}}
+ `, + styleUrls: ['app/app.component.css'] + }) + export class AppComponent implements OnInit{ + title = 'Tour of Heroes'; + + heroes: Hero[] = []; + + ngOnInit() { + getHeroes().then(heroes => this.heroes = heroes); + } + } + + bootstrap(AppComponent, []); + + function getHeroes() { + return // some promise of data; + } +// #enddocregion 001-1 + + +// #docregion 001-2 + /* recommended */ + + // main.ts + import { bootstrap } from 'angular2/platform/browser'; + import { AppComponent } from './app.component'; + + bootstrap(AppComponent, []); + /* recommended */ + + // app.component.ts + import { Component, OnInit } from 'angular2/core'; + + import { Hero } from './hero'; + import { HeroService } from './hero.service'; + + @Component({ + selector: 'my-app', + template: ` +
{{heroes | json}}
+ `, + styleUrls: ['app/app.component.css'], + providers: [HeroService] + }) + export class AppComponent implements OnInit{ + heroes: Hero[] = []; + + constructor(private _heroService: HeroService) {} + + ngOnInit() { + this._heroService.getHeroes() + .then(heroes => this.heroes = heroes); + } + } +// #enddocregion 001-2 + +// #docregion 001-3 + /* recommended */ + + // hero.service.ts + import { Injectable } from 'angular2/core'; + import { HEROES } from './mock-heroes'; + + @Injectable() + export class HeroService { + getHeroes() { + return Promise.resolve(HEROES); + } + } +// #enddocregion 001-3 + +// #docregion 001-4 + /* recommended */ + + // hero.ts + export class Hero { + id: number; + name: string; + } +// #enddocregion 001-4 diff --git a/public/docs/_examples/router/ts/example-config.json b/public/docs/_examples/style-guide/ts/example-config.json similarity index 100% rename from public/docs/_examples/router/ts/example-config.json rename to public/docs/_examples/style-guide/ts/example-config.json diff --git a/public/docs/_examples/router/ts/index.html b/public/docs/_examples/style-guide/ts/index.html similarity index 97% rename from public/docs/_examples/router/ts/index.html rename to public/docs/_examples/style-guide/ts/index.html index dae130f8aa..80a3e1af46 100644 --- a/public/docs/_examples/router/ts/index.html +++ b/public/docs/_examples/style-guide/ts/index.html @@ -7,7 +7,7 @@ - Router Sample + Style Guide Sample diff --git a/public/docs/_examples/style-guide/ts/plnkr.json b/public/docs/_examples/style-guide/ts/plnkr.json new file mode 100644 index 0000000000..334ad918b8 --- /dev/null +++ b/public/docs/_examples/style-guide/ts/plnkr.json @@ -0,0 +1,8 @@ +{ + "description": "Style Guide", + "files":[ + "!**/*.d.ts", + "!**/*.js" + ], + "tags": ["style guide, styleguide"] +} \ No newline at end of file diff --git a/public/docs/dart/latest/guide/_data.json b/public/docs/dart/latest/guide/_data.json index fca35dcc06..e481574fa2 100644 --- a/public/docs/dart/latest/guide/_data.json +++ b/public/docs/dart/latest/guide/_data.json @@ -103,7 +103,13 @@ "title": "Structural Directives", "intro": "Angular has a powerful template engine that lets us easily manipulate the DOM structure of our elements." }, - + + "style-guide": { + "title": "Style Guide", + "intro": "Write Angular 2 with style.", + "hide": true + }, + "testing": { "title": "Testing", "intro": "Techniques and practices for testing an Angular 2 app", diff --git a/public/docs/dart/latest/guide/style-guide.jade b/public/docs/dart/latest/guide/style-guide.jade new file mode 100644 index 0000000000..f8df2a84a6 --- /dev/null +++ b/public/docs/dart/latest/guide/style-guide.jade @@ -0,0 +1 @@ +!= partial("../../../_includes/_ts-temp") \ No newline at end of file diff --git a/public/docs/js/latest/guide/_data.json b/public/docs/js/latest/guide/_data.json index f92809bc9e..1396c0c55e 100644 --- a/public/docs/js/latest/guide/_data.json +++ b/public/docs/js/latest/guide/_data.json @@ -102,7 +102,13 @@ "title": "Structural Directives", "intro": "Angular has a powerful template engine that lets us easily manipulate the DOM structure of our elements." }, - + + "style-guide": { + "title": "Style Guide", + "intro": "Write Angular 2 with style.", + "hide": true + }, + "testing": { "title": "Testing", "intro": "Techniques and practices for testing an Angular 2 app", diff --git a/public/docs/js/latest/guide/style-guide.jade b/public/docs/js/latest/guide/style-guide.jade new file mode 100644 index 0000000000..f8df2a84a6 --- /dev/null +++ b/public/docs/js/latest/guide/style-guide.jade @@ -0,0 +1 @@ +!= partial("../../../_includes/_ts-temp") \ No newline at end of file diff --git a/public/docs/ts/latest/guide/_data.json b/public/docs/ts/latest/guide/_data.json index 5366524e6b..2ced3f717b 100644 --- a/public/docs/ts/latest/guide/_data.json +++ b/public/docs/ts/latest/guide/_data.json @@ -103,6 +103,12 @@ "intro": "Angular has a powerful template engine that lets us easily manipulate the DOM structure of our elements." }, + "style-guide": { + "title": "Style Guide", + "intro": "Write Angular 2 with style.", + "hide": true + }, + "testing": { "title": "Testing", "intro": "Techniques and practices for testing an Angular 2 app" diff --git a/public/docs/ts/latest/guide/style-guide.jade b/public/docs/ts/latest/guide/style-guide.jade new file mode 100644 index 0000000000..e1423af810 --- /dev/null +++ b/public/docs/ts/latest/guide/style-guide.jade @@ -0,0 +1,665 @@ +include ../_util-fns + +:marked + Welcome to the Angular 2 Guide of Style + + ## Purpose + + If you are looking for an opinionated style guide for syntax, conventions, and structuring Angular applications, then step right in. + + The purpose of this style guide is to provide guidance on building Angular applications by showing the conventions we use and, more importantly, why we choose them. +.l-main-section +a(id='toc') +:marked + ## Table of Contents + + 1. [Single Responsibility](#single-responsibility) + 1. [Components](#components) + 1. [Services](#services) + 1. [Data Services](#data-services) + 1. [Naming](#naming) + 1. [Application Structure LIFT Principle](#application-structure-lift-principle) + 1. [Application Structure](#application-structure) + 1. [Appendix](#appendix) +:marked + ## Single Responsibility + + ### Rule of 1 + + #### Style 001 + + Define 1 component per file, recommended to be less than 400 lines of code. + + **Why?** One component per file promotes easier unit testing and mocking. + + **Why?** One component per file makes it far easier to read, maintain, and avoid collisions with teams in source control. + + **Why?** One component per file avoids hidden bugs that often arise when combining components in a file where they may share variables, create unwanted closures, or unwanted coupling with dependencies. + + The following example defines the `AppComponent`, handles the bootstrapping, and shared functions all in the same file. + + The key is to make the code more reusable, easier to read, and less mistake prone. + ++makeExample('style-guide/ts/001/app/placeholder.ts', '001-1', 'app.component.ts (component)') +:marked + The same components are now separated into their own files. + ++makeTabs( + 'style-guide/ts/001/app/main.ts,style-guide/ts/001/app/app.component.ts,style-guide/ts/001/app/hero.service.ts,style-guide/ts/001/app/hero.model.ts', + '', + 'app/main.ts, app/app.component.ts, app/hero.service.ts, app/hero.model.ts') +:marked + As the app grows, this rule becomes even more important. + +Back to top + +:marked + ### Small Functions + + #### Style 002 + + - Define small functions, no more than 75 LOC (less is better). + + **Why?** Small functions are easier to test, especially when they do one thing and serve one purpose. + + **Why?** Small functions promote reuse. + + **Why?** Small functions are easier to read. + + **Why?** Small functions are easier to maintain. + + **Why?** Small functions help avoid hidden bugs that come with large functions that share variables with external scope, create unwanted closures, or unwanted coupling with dependencies. + +Back to top +:marked + ## Components + + ### Member Sequence + + #### Style 033 + + - Place properties up top followed by methods. Private members should follow public members, alphabetized. + + **Why?** Placing members in a consistent sequence makes it easy to read and helps you instantly identify which members of the component serve which purpose. + + ```typescript + /* recommended */ + export class ToastComponent implements OnInit { + // public properties + message: string; + title: string; + + // private fields + private _defaults = { + title: '', + message: 'May the Force be with You' + }; + private _toastElement: any; + + // ctor + constructor(private _toastService: ToastService) { } + + // public methods + activate(message = this._defaults.message, title = this._defaults.title) { + this.title = title; + this.message = message; + this._show(); + } + + ngOnInit() { + this._toastElement = document.getElementById('toast'); + } + + // private methods + private _show() { + console.log(this.message); + this._toastElement.style.opacity = 1; + this._toastElement.style.zIndex = 9999; + + window.setTimeout(() => this._hide(), 2500); + } + + private _hide() { + this._toastElement.style.opacity = 0; + window.setTimeout(() => this._toastElement.style.zIndex = 0, 400); + } + } + ``` + +Back to top +:marked + ### Defer Logic to Services + + #### Style 035 + + - Defer logic in a component by delegating to services. + + - Move reusable logic to services and keep components simple and focused on their intended purpose. + + **Why?** Logic may be reused by multiple components when placed within a service and exposed via a function. + + **Why?** Logic in a service can more easily be isolated in a unit test, while the calling logic in the component can be easily mocked. + + **Why?** Removes dependencies and hides implementation details from the component. + + **Why?** Keeps the component slim, trim, and focused. + + ```typescript + // avoid + export class SessionListComponent implements OnInit { + sessions: Session[]; + + constructor(private _http: Http) { } + + getSessions() { + this.sessions = []; + this._http.get(sessionsUrl) + .map((response: Response) => response.json().data) + .catch(this._exceptionService.catchBadResponse) + .finally(() => this._spinnerService.hide()) + .subscribe(sessions => this.sessions = sessions); + } + + + ngOnInit() { + this.getSessions(); + } + } + ``` + + ```typescript + // recommended + export class SessionListComponent implements OnInit { + sessions: Session[]; + + constructor(private _sessionService: SessionService) { } + + getSessions() { + this.sessions = []; + this._sessionService.getSessions() + .subscribe(sessions => this.sessions = sessions); + } + + ngOnInit() { + this.getSessions(); + } + } + ``` + +Back to top + +:marked + ## Services + + ### Singletons + + #### Style 040 + + - Services are singletons withint he same injector. They should be used for sharing data and functionality. + + ```typescript + // service + import { Injectable } from 'angular2/core'; + import { Session } from './session'; + + @Injectable() + export class HeroService { + getHeroes() { + return this._http.get('api/sessions') + .map((response: Response) => response.json().data) + } + } + ``` + +Back to top + +:marked + ### Providing a Service + + #### Style 041 + + - Services should be provided to the Angular 2 injector at the top-most component where they will be shared. + + **Why?** The Angular 2 injector is hierarchical. + + **Why?** When providing the service to a top level component, that instance is shared and available to all child components of that top level component. + + **Why?** This is ideal when a service is sharing methods and has no state, or state that must be shared. + + **Why?** This is not ideal when two different components need different instances of a service. In this scenario it would be better to provide the service at the component level that needs the new and separate instance. + + ```typescript + /* recommended */ + + // app.component.ts + import { Component } from 'angular2/core'; + + import { SpeakerListComponent } from './speakers/speaker-list.component'; + import { SpeakerService } from './common/speaker.service'; + + @Component({ + selector: 'my-app', + template: ` + + `, + directives: [SpeakerListComponent], + providers: [SpeakerService] + }) + export class AppComponent { } + ``` + + ```typescript + /* recommended */ + + // speaker-list.component.ts + import { Component, OnInit } from 'angular2/core'; + + import { SpeakerService } from './common/speaker.service'; + import { Speaker } from './common/speaker'; + + @Component({ + selector: 'my-speakers', + template: ` +
{{speakers | json}}
+ ` + }) + export class SpeakerListComponent implements OnInit{ + speakers: Speaker[] = []; + + constructor(private _speakerService: SpeakerService) {} + + ngOnInit() { + this._speakerService.getSpeakers().then(speakers => this.speakers = speakers); + } + } + ``` + +Back to top +:marked + ### Single Responsibility + + #### Style 042 + + - Services should have a [single responsibility](https://en.wikipedia.org/wiki/Single_responsibility_principle), that is encapsulated by its context. Once a service begins to exceed that singular purpose, a new one should be created. + +Back to top +:marked + ## Data Services + + ### Separate Data Calls + + #### Style 050 + + - Refactor logic for making data operations and interacting with data to a service. Make data services responsible for XHR calls, local storage, stashing in memory, or any other data operations. + + **Why?** The component's responsibility is for the presentation and gathering of information for the view. It should not care how it gets the data, just that it knows who to ask for it. Separating the data services moves the logic on how to get it to the data service, and lets the component be simpler and more focused on the view. + + **Why?** This makes it easier to test (mock or real) the data calls when testing a component that uses a data service. + + **Why?** Data service implementation may have very specific code to handle the data repository. This may include headers, how to talk to the data, or other services such as `Http`. Separating the logic into a data service encapsulates this logic in a single place hiding the implementation from the outside consumers (perhaps a component), also making it easier to change the implementation. + + ```typescript + // recommended + export class SessionListComponent implements OnInit { + sessions: Session[]; + filteredSessions = this.sessions; + + constructor(private _sessionService: SessionService) { } + + getSessions() { + this.sessions = []; + this._sessionService.getSessions() + .subscribe(sessions => { + this.sessions = this.filteredSessions = sessions; + }, + error => { + console.log('error occurred here'); + console.log(error); + }, + () => { + console.log('completed'); + }); + } + + ngOnInit() { + this.getSessions(); + } + } + ``` + +Back to top +:marked + ## Naming + + ### Naming Guidelines + + #### Style 100 + + - Use consistent names for all components following a pattern that describes the component's feature then (optionally) its type. My recommended pattern is `feature.type.js`. There are 2 names for most assets: + * the file name (`avengers.component.ts`) + * the registered component name with Angular (`Component`) + + **Why?** Naming conventions help provide a consistent way to find content at a glance. Consistency within the project is vital. Consistency with a team is important. Consistency across a company provides tremendous efficiency. + + **Why?** The naming conventions should simply help you find your code faster and make it easier to understand. + + **Why?** Names of folders and files should clearly convey their intent. For example, `app/speakers/speaker-list.component.ts` may contain a component that manages a list of speakers. + +Back to top +:marked + ### File Names + + #### Style 101 + + - Use consistent names for all components following a pattern that describes the component's feature then (optionally) its type. A recommended pattern is `feature.type.ts`. + + - Use conventional suffixes including `*.service.ts`, `*.component.ts`, `*.pipe.ts`. Invent other suffixes where desired for your team, but take care in having too many. + + - use dashes to separate words and dots to separate the descriptive name from the type. + + **Why?** Provides a consistent way to quickly identify components. + + **Why?** Provides a consistent way to quickly find components using an editor or IDE's fuzzy search techniques. + + **Why?** Provides pattern matching for any automated tasks. + + ``` + // recommended + + // Bootstrapping file and main entry point + main.ts + + // Components + speakers.component.ts + speaker-list.component.ts + speaker-detail.component.ts + + // Services + logger.service.ts + speaker.service.ts + exception.service.ts + filter-text.service.ts + + // Models + session.ts + speaker.ts + + // Pipes + ellipsis.pipe.ts + init-caps.pipe.ts + ``` + +Back to top +:marked + ### Test File Names + + #### Style 102 + + - Name test specifications similar to the component they test with a suffix of `spec`. + + **Why?** Provides a consistent way to quickly identify components. + + **Why?** Provides pattern matching for [karma](http://karma-runner.github.io/) or other test runners. + + ``` + // recommended + + // Components + speakers.component.spec.ts + speaker-list.component.spec.ts + speaker-detail.component.spec.ts + + // Services + logger.service.spec.ts + speaker.service.spec.ts + exception.service.spec.ts + filter-text.service.spec.ts + + // Pipes + ellipsis.pipe.spec.ts + init-caps.pipe.spec.ts + ``` + +Back to top +:marked + ### Component Names + + #### Style 103 + + - Use consistent names for all components named after their feature. Use UpperCamelCase for components' symbols. Match the name of the component to the naming of the file + + **Why?** Provides a consistent way to quickly identify and reference components. + + **Why?** UpperCamelCase is conventional for identifying object that can be instantiated using a constructor. + + ```typescript + AppComponent //app.component.ts + SpeakersComponent //speakers.component.ts + SpeakerListComponent //speaker-list.component.ts + SpeakerDetailComponent //speaker-detail.component.ts + ``` + +Back to top +:marked + ### Suffixes + + #### Style 104 + + - Append the component name with the suffix `Component`. + + **Why?** The `Component` suffix is more commonly used and is more explicitly descriptive. + + ```typescript + // recommended + + // speaker-list.component.ts + export class SpeakerListComponent { } + ``` + +Back to top +:marked + ### Service Names + + #### Style 110 + + - Use consistent names for all services named after their feature. Use UpperCamelCase for services. Suffix services with `Service` when it is not clear what they are (e.g. when they are nouns). + + **Why?** Provides a consistent way to quickly identify and reference services. + + **Why?** Clear service names such as `logger` do not require a suffix. + + **Why?** Service names such as `Credit` are nouns and require a suffix and should be named with a suffix when it is not obvious if it is a service or something else. + + ```typescript + SpeakerService // speaker.service.ts + CreditService // credit.service.ts + Logger // logger.service.ts + ``` + +Back to top +:marked + ## Routing + Client-side routing is important for creating a navigation flow between a component tree hierarchy, and composing components that are made of many other child components. + +Back to top +:marked + ### Component Router + + #### Style 130 + + - Separate route configuration into a routing component file, also known as a component router. + + - Use a `` in the component router, where the routes will have their component targets display their templates. + + - Focus the logic in the component router to the routing aspects and its target components. Extract other logic to services and other components. + + **Why?** A component that handles routing is known as the component router, thus this follows the Angular 2 routing pattern. + + **Why?** A component that handles routing is known as the componenter router. + + **Why?** The `` indicates where the tempalte should be displayed for the target route. + + ```typescript + import { Component } from 'angular2/core'; + import { RouteConfig, ROUTER_DIRECTIVES, ROUTER_PROVIDERS } from 'angular2/router'; + + import { SpeakersComponent, SpeakerService } from './+speakers'; + import { DashboardComponent } from './+dashboard'; + import { NavComponent } from './layout/nav.component'; + + @Component({ + selector: 'my-app', + templateUrl: 'app/app.component.html', + styleUrls: ['app/app.component.css'], + directives: [ROUTER_DIRECTIVES, NavComponent], + providers: [ + ROUTER_PROVIDERS, + SpeakerService + ] + }) + @RouteConfig([ + { path: '/dashboard', name: 'Dashboard', component: DashboardComponent, useAsDefault: true }, + { path: '/speakers/...', name: 'Speakers', component: SpeakersComponent }, + ]) + export class AppComponent { } + ``` + +Back to top +:marked + ### Route Naming + + #### Style 131 + + - Use the naming convention for the routes with the component name without the Component suffix. + + **Why?** This maps the route name to the component and makes it easy to identify. + + ```typescript + { path: '/dashboard', name: 'Dashboard', component: DashboardComponent } + ``` + +Back to top +:marked + ## Application Structure LIFT Principle + ### LIFT + + #### Style 140 + + - Structure your app such that you can `L`ocate your code quickly, `I`dentify the code at a glance, keep the `F`lattest structure you can, and `T`ry to stay DRY. The structure should follow these 4 basic guidelines, listed in order of importance. + + *Why LIFT?*: Provides a consistent structure that scales well, is modular, and makes it easier to increase developer efficiency by finding code quickly. Another way to check your app structure is to ask yourself: How quickly can you open and work in all of the related files for a feature? + +Back to top +:marked + ### Locate + + #### Style 141 + + - Make locating your code intuitive, simple and fast. + + **Why?** I find this to be super important for a project. If the team cannot find the files they need to work on quickly, they will not be able to work as efficiently as possible, and the structure needs to change. You may not know the file name or where its related files are, so putting them in the most intuitive locations and near each other saves a ton of time. A descriptive folder structure can help with this. + + ``` + /node_modules + /client + /app + /avengers + /blocks + /exception + /logger + /core + /dashboard + /data + /layout + /widgets + /content + index.html + package.json + ``` + +Back to top +:marked + ### Identify + + #### Style 142 + + - When you look at a file you should instantly know what it contains and represents. + + **Why?** You spend less time hunting and pecking for code, and become more efficient. If this means you want longer file names, then so be it. Be descriptive with file names and keeping the contents of the file to exactly 1 component. Avoid files with multiple controllers, multiple services, or a mixture. There are deviations of the 1 per file rule when I have a set of very small features that are all related to each other, they are still easily identifiable. + +Back to top +:marked + ### Flat + + #### Style 143 + + - Keep a flat folder structure as long as possible. When you get to 7+ files, begin considering separation. + + **Why?** Nobody wants to search 7 levels of folders to find a file. Think about menus on web sites … anything deeper than 2 should take serious consideration. In a folder structure there is no hard and fast number rule, but when a folder has 7-10 files, that may be time to create subfolders. Base it on your comfort level. Use a flatter structure until there is an obvious value (to help the rest of LIFT) in creating a new folder. + +Back to top +:marked + ### T-DRY (Try to Stick to DRY) + + #### Style 144 + + - Be DRY, but don't go nuts and sacrifice readability. + + **Why?** Being DRY is important, but not crucial if it sacrifices the others in LIFT, which is why I call it T-DRY. I don’t want to type session-view.html for a view because, well, it’s obviously a view. If it is not obvious or by convention, then I name it. + +Back to top +:marked + ## Application Structure + + ### Overall Guidelines + + #### Style 150 + + - Have a near term view of implementation and a long term vision. In other words, start small but keep in mind on where the app is heading down the road. All of the app's code goes in a root folder named `app`. All content is 1 feature per file. Each component, service, pipe is in its own file. All 3rd party vendor scripts are stored in another root folder and not in the `app` folder. I didn't write them and I don't want them cluttering my app. + + **example coming soon** + +Back to top +:marked + ### Layout + + #### Style 151 + + - Place components that define the overall layout of the application in a folder named `layout`. These may include a shell view and component may act as the container for the app, navigation, menus, content areas, and other regions. + + **Why?** Organizes all layout in a single place re-used throughout the application. + +Back to top +:marked + ### Folders-by-Feature Structure + + #### Style 152 + + - Create folders named for the feature they represent. When a folder grows to contain more than 7 files, start to consider creating a folder for them. Your threshold may be different, so adjust as needed. + + **Why?** A developer can locate the code, identify what each file represents at a glance, the structure is flat as can be, and there is no repetitive nor redundant names. + + **Why?** The LIFT guidelines are all covered. + + **Why?** Helps reduce the app from becoming cluttered through organizing the content and keeping them aligned with the LIFT guidelines. + + **Why?** When there are a lot of files (10+) locating them is easier with a consistent folder structures and more difficult in flat structures. + + **example coming soon** + +Back to top +:marked + ## Appendix + + ### File Templates and Snippets + Use file templates or snippets to help follow consistent styles and patterns. Here are templates and/or snippets for some of the web development editors and IDEs. + + ### Visual Studio Code + + - [Visual Studio Code](https://code.visualstudio.com/) snippets that follow these styles and guidelines. + + - [Snippets for VS Code](https://marketplace.visualstudio.com/items?itemName=johnpapa.Angular2) + + [![Use Extension](https://github.com/johnpapa/vscode-angular2-snippets/raw/master/images/use-extension.gif)](https://marketplace.visualstudio.com/items?itemName=johnpapa.Angular2) + +Back to top From dd7b5176a82c4825dbc5d1aeb8e4287d8d64dbf3 Mon Sep 17 00:00:00 2001 From: Ward Bell Date: Sun, 10 Apr 2016 15:04:04 -0700 Subject: [PATCH 2/5] docs(testing): add tests that involve Angular 2 --- public/docs/_examples/.gitignore | 1 + public/docs/_examples/karma-test-shim.js | 121 +++-- public/docs/_examples/karma.conf.js | 97 ++-- public/docs/_examples/karma.js.conf.js | 68 --- public/docs/_examples/karma.ts.conf.js | 70 --- public/docs/_examples/package.json | 5 +- public/docs/_examples/protractor-conf.old.js | 24 - .../ts/app/toh/hero.service.1.ts | 10 +- .../ts/app/toh/hero.service.ts | 33 +- public/docs/_examples/testing/ts/app/hero.ts | 2 +- .../testing/ts/app/http-hero.service.spec.ts | 148 ++++++ .../testing/ts/app/http-hero.service.ts | 44 ++ .../ts/app/public-external-template.html | 1 + .../_examples/testing/ts/app/public.spec.ts | 458 ++++++++++++++++++ .../docs/_examples/testing/ts/app/public.ts | 133 +++++ public/docs/_examples/testing/ts/test-shim.js | 48 ++ .../testing/ts/unit-tests-public.html | 32 ++ 17 files changed, 1035 insertions(+), 260 deletions(-) delete mode 100644 public/docs/_examples/karma.js.conf.js delete mode 100644 public/docs/_examples/karma.ts.conf.js delete mode 100644 public/docs/_examples/protractor-conf.old.js create mode 100644 public/docs/_examples/testing/ts/app/http-hero.service.spec.ts create mode 100644 public/docs/_examples/testing/ts/app/http-hero.service.ts create mode 100644 public/docs/_examples/testing/ts/app/public-external-template.html create mode 100644 public/docs/_examples/testing/ts/app/public.spec.ts create mode 100644 public/docs/_examples/testing/ts/app/public.ts create mode 100644 public/docs/_examples/testing/ts/test-shim.js create mode 100644 public/docs/_examples/testing/ts/unit-tests-public.html diff --git a/public/docs/_examples/.gitignore b/public/docs/_examples/.gitignore index d821c82bea..a574567c52 100644 --- a/public/docs/_examples/.gitignore +++ b/public/docs/_examples/.gitignore @@ -10,3 +10,4 @@ tsconfig.json tslint.json npm-debug*. **/protractor.config.js +_test-output diff --git a/public/docs/_examples/karma-test-shim.js b/public/docs/_examples/karma-test-shim.js index 8ccb27a727..932744bc69 100644 --- a/public/docs/_examples/karma-test-shim.js +++ b/public/docs/_examples/karma-test-shim.js @@ -1,68 +1,91 @@ -// Tun on full stack traces in errors to help debugging -Error.stackTraceLimit=Infinity; +/*global jasmine, __karma__, window*/ +(function () { +// Error.stackTraceLimit = Infinity; jasmine.DEFAULT_TIMEOUT_INTERVAL = 1000; -// // Cancel Karma's synchronous start, -// // we will call `__karma__.start()` later, once all the specs are loaded. -__karma__.loaded = function() {}; +// Cancel Karma's synchronous start, +// we call `__karma__.start()` later, once all the specs are loaded. +__karma__.loaded = function () { }; +// SET THE RUNTIME APPLICATION ROOT HERE +var appRoot ='app'; // no trailing slash! -System.config({ - packages: { - 'base/app': { - defaultExtension: false, - // removed because of issues with raw .js files not being found. - // format: 'register', - map: Object.keys(window.__karma__.files). - filter(onlyAppFiles). - reduce(function createPathRecords(pathsMapping, appPath) { - // creates local module name mapping to global path with karma's fingerprint in path, e.g.: - // './hero.service': '/base/src/app/hero.service.js?f4523daf879cfb7310ef6242682ccf10b2041b3e' - var moduleName = appPath.replace(/^\/base\/app\//, './').replace(/\.js$/, ''); - pathsMapping[moduleName] = appPath + '?' + window.__karma__.files[appPath] - return pathsMapping; - }, {}) +// RegExp for client application base path within karma (which always starts 'base\') +var karmaBase = '^\/base\/'; // RegEx string for base of karma folders +var appPackage = 'base/' + appRoot; //e.g., base/app +var appRootRe = new RegExp(karmaBase + appRoot + '\/'); +var onlyAppFilesRe = new RegExp(karmaBase + appRoot + '\/(?!.*\.spec\.js$)([a-z0-9-_\.\/]+)\.js$'); - } - } -}); +var moduleNames = []; -// old code from angular 44 -// System.import('angular2/src/core/dom/browser_adapter').then(function(browser_adapter) { -// new path for angular 51 -System.import('angular2/src/platform/browser/browser_adapter').then(function(browser_adapter) { - browser_adapter.BrowserDomAdapter.makeCurrent(); -}).then(function() { +// Configure systemjs packages to use the .js extension for imports from the app folder +var packages = {}; +packages[appPackage] = { + defaultExtension: false, + format: 'register', + map: Object.keys(window.__karma__.files) + .filter(onlyAppFiles) + // Create local module name mapping to karma file path for app files + // with karma's fingerprint in query string, e.g.: + // './hero.service': '/base/app/hero.service.js?f4523daf879cfb7310ef6242682ccf10b2041b3e' + .reduce(function (pathsMapping, appPath) { + var moduleName = appPath.replace(appRootRe, './').replace(/\.js$/, ''); + pathsMapping[moduleName] = appPath + '?' + window.__karma__.files[appPath]; + return pathsMapping; + }, {}) + } + +System.config({ packages: packages }); + +// Configure Angular for the browser and +// with test versions of the platform providers +System.import('angular2/testing') + .then(function (testing) { + return System.import('angular2/platform/testing/browser') + .then(function (providers) { + testing.setBaseTestProviders( + providers.TEST_BROWSER_PLATFORM_PROVIDERS, + providers.TEST_BROWSER_APPLICATION_PROVIDERS + ); + }); + }) + +// Load all spec files +// (e.g. 'base/app/hero.service.spec.js') +.then(function () { return Promise.all( - Object.keys(window.__karma__.files) // All files served by Karma. - .filter(onlySpecFiles) - // .map(filePath2moduleName) // Normalize paths to module names. - .map(function(moduleName) { - // loads all spec files via their global module names (e.g. 'base/src/app/hero.service.spec') - return System.import(moduleName); - })); + Object.keys(window.__karma__.files) + .filter(onlySpecFiles) + .map(function (moduleName) { + moduleNames.push(moduleName); + return System.import(moduleName); + })); }) -.then(function() { - __karma__.start(); -}, function(error) { - __karma__.error(error.stack || error); -}); +.then(success, fail); -function filePath2moduleName(filePath) { - return filePath. - replace(/^\//, ''). // remove / prefix - replace(/\.\w+$/, ''); // remove suffix -} - +////// Helpers ////// function onlyAppFiles(filePath) { - return /^\/base\/app\/.*\.js$/.test(filePath) && !onlySpecFiles(filePath); + return onlyAppFilesRe.test(filePath); } - function onlySpecFiles(filePath) { return /\.spec\.js$/.test(filePath); } + +function success () { + console.log( + 'Spec files loaded:\n ' + + moduleNames.join('\n ') + + '\nStarting Jasmine testrunner'); + __karma__.start(); +} + +function fail(error) { + __karma__.error(error.stack || error); +} + +})(); diff --git a/public/docs/_examples/karma.conf.js b/public/docs/_examples/karma.conf.js index 5b07bee380..e128ca2fb3 100644 --- a/public/docs/_examples/karma.conf.js +++ b/public/docs/_examples/karma.conf.js @@ -1,43 +1,82 @@ module.exports = function(config) { + + var appBase = 'app/'; // transpiled app JS files + var appAssets ='base/app/'; // component assets fetched by Angular's compiler + config.set({ - basePath: '', - frameworks: ['jasmine'], - - files: [ - // paths loaded by Karma - {pattern: 'node_modules/systemjs/dist/system.src.js', included: true, watched: true}, - {pattern: 'node_modules/angular2/bundles/angular2.js', included: true, watched: true}, - {pattern: 'node_modules/angular2/bundles/testing.js', included: true, watched: true}, - {pattern: 'karma-test-shim.js', included: true, watched: true}, - {pattern: 'app/test/*.js', included: true, watched: true}, - - // paths loaded via module imports - {pattern: 'app/**/*.js', included: false, watched: true}, - - // paths loaded via Angular's component compiler - // (these paths need to be rewritten, see proxies section) - {pattern: 'app/**/*.html', included: false, watched: true}, - {pattern: 'app/**/*.css', included: false, watched: true}, - - // paths to support debugging with source maps in dev tools - {pattern: 'app/**/*.ts', included: false, watched: false}, - {pattern: 'app/**/*.js.map', included: false, watched: false} + plugins: [ + require('karma-jasmine'), + require('karma-chrome-launcher'), + require('karma-htmlfile-reporter') ], - // proxied base paths - proxies: { - // required for component assests fetched by Angular's compiler - "/app/": "/base/app/" + customLaunchers: { + // From the CLI. Not used here but interesting + // chrome setup for travis CI using chromium + Chrome_travis_ci: { + base: 'Chrome', + flags: ['--no-sandbox'] + } }, - reporters: ['progress'], - port: 9877, + files: [ + // Angular and shim libraries loaded by Karma + { pattern: 'node_modules/systemjs/dist/system-polyfills.js', included: true, watched: true }, + { pattern: 'node_modules/systemjs/dist/system.src.js', included: true, watched: true }, + { pattern: 'node_modules/es6-shim/es6-shim.js', included: true, watched: true }, + { pattern: 'node_modules/angular2/bundles/angular2-polyfills.js', included: true, watched: true }, + { pattern: 'node_modules/rxjs/bundles/Rx.js', included: true, watched: true }, + { pattern: 'node_modules/angular2/bundles/angular2.js', included: true, watched: true }, + { pattern: 'node_modules/angular2/bundles/testing.dev.js', included: true, watched: true }, + + // External libraries loaded by Karma + { pattern: 'node_modules/angular2/bundles/http.dev.js', included: true, watched: true }, + { pattern: 'node_modules/angular2/bundles/router.dev.js', included: true, watched: true }, + { pattern: 'node_modules/a2-in-memory-web-api/web-api.js', included: true, watched: true }, + + // Configures module loader w/ app and specs, then launch karma + { pattern: 'karma-test-shim.js', included: true, watched: true }, + + // transpiled application & spec code paths loaded via module imports + {pattern: appBase + '**/*.js', included: false, watched: true}, + + // asset (HTML & CSS) paths loaded via Angular's component compiler + // (these paths need to be rewritten, see proxies section) + {pattern: appBase + '**/*.html', included: false, watched: true}, + {pattern: appBase + '**/*.css', included: false, watched: true}, + + // paths for debugging with source maps in dev tools + {pattern: appBase + '**/*.ts', included: false, watched: false}, + {pattern: appBase + '**/*.js.map', included: false, watched: false} + ], + + // proxied base paths for loading assets + proxies: { + // required for component assets fetched by Angular's compiler + "/app/": appAssets + }, + + exclude: [], + preprocessors: {}, + reporters: ['progress', 'html'], + + // HtmlReporter configuration + htmlReporter: { + // Open this file to see results in browser + outputFile: '_test-output/tests.html', + + // Optional + pageTitle: 'Unit Tests', + subPageTitle: __dirname + }, + + port: 9876, colors: true, logLevel: config.LOG_INFO, autoWatch: true, browsers: ['Chrome'], - singleRun: true + singleRun: false }) } diff --git a/public/docs/_examples/karma.js.conf.js b/public/docs/_examples/karma.js.conf.js deleted file mode 100644 index e55127f0f0..0000000000 --- a/public/docs/_examples/karma.js.conf.js +++ /dev/null @@ -1,68 +0,0 @@ -// Karma configuration -// Generated on Mon Aug 10 2015 11:36:40 GMT-0700 (Pacific Daylight Time) - -module.exports = function(config) { - config.set({ - - // base path that will be used to resolve all patterns (eg. files, exclude) - basePath: '', - - - // frameworks to use - // available frameworks: https://npmjs.org/browse/keyword/karma-adapter - frameworks: ['jasmine'], - - - // list of files / patterns to load in the browser - files: [ - { pattern: 'https://code.angularjs.org/2.0.0-alpha.34/angular2.sfx.dev.js', watched: false }, - - '**/js/*.js', - ], - - - // list of files to exclude - exclude: [ - '**/*.e2e-spec.js' - ], - - - // preprocess matching files before serving them to the browser - // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor - preprocessors: { - }, - - - // test results reporter to use - // possible values: 'dots', 'progress' - // available reporters: https://npmjs.org/browse/keyword/karma-reporter - reporters: ['progress'], - - - // web server port - port: 9876, - - - // enable / disable colors in the output (reporters and logs) - colors: true, - - - // level of logging - // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG - logLevel: config.LOG_INFO, - - - // enable / disable watching file and executing tests whenever any file changes - autoWatch: true, - - - // start these browsers - // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher - browsers: ['Chrome'], - - - // Continuous Integration mode - // if true, Karma captures browsers, runs the tests and exits - singleRun: false - }) -} diff --git a/public/docs/_examples/karma.ts.conf.js b/public/docs/_examples/karma.ts.conf.js deleted file mode 100644 index 5b2d176b56..0000000000 --- a/public/docs/_examples/karma.ts.conf.js +++ /dev/null @@ -1,70 +0,0 @@ -// Karma configuration -// Generated on Mon Aug 10 2015 11:36:40 GMT-0700 (Pacific Daylight Time) - -module.exports = function(config) { - config.set({ - - // base path that will be used to resolve all patterns (eg. files, exclude) - basePath: '', - - - // frameworks to use - // available frameworks: https://npmjs.org/browse/keyword/karma-adapter - frameworks: ['jasmine'], - - - // list of files / patterns to load in the browser - files: [ - { pattern: 'https://github.jspm.io/jmcriffey/bower-traceur-runtime@0.0.87/traceur-runtime.js', watched: false }, - { pattern: 'https://jspm.io/system@0.16.js', watched: false }, - { pattern: 'https://code.angularjs.org/2.0.0-alpha.34/angular2.dev.js', watched: false }, - - '**/ts/**/*.spec.js' - ], - - - // list of files to exclude - exclude: [ - '**/*.e2e-spec.js' - ], - - - // preprocess matching files before serving them to the browser - // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor - preprocessors: { - }, - - - // test results reporter to use - // possible values: 'dots', 'progress' - // available reporters: https://npmjs.org/browse/keyword/karma-reporter - reporters: ['progress'], - - - // web server port - port: 9876, - - - // enable / disable colors in the output (reporters and logs) - colors: true, - - - // level of logging - // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG - logLevel: config.LOG_INFO, - - - // enable / disable watching file and executing tests whenever any file changes - autoWatch: true, - - - // start these browsers - // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher - browsers: ['Chrome'], - - - // Continuous Integration mode - // if true, Karma captures browsers, runs the tests and exits - singleRun: false - }) -} diff --git a/public/docs/_examples/package.json b/public/docs/_examples/package.json index 92908d0c30..a5e20d4c6f 100644 --- a/public/docs/_examples/package.json +++ b/public/docs/_examples/package.json @@ -4,12 +4,12 @@ "description": "Master package.json, the superset of all dependencies for all of the _example package.json files.", "main": "index.js", "scripts": { - "start": "tsc && concurrently \"npm run tsc:w\" \"npm run lite\" ", + "start": "tsc && concurrently \"tsc -w\" \"lite-server\" ", "tsc": "tsc", "tsc:w": "tsc -w", "lite": "lite-server", "live": "live-server", - "test": "karma start karma.conf.js", + "test": "tsc && concurrently \"tsc -w\" \"karma start karma.conf.js\"", "build-and-test": "npm run tsc && npm run test", "http-server": "tsc && http-server", "http-server:e2e": "http-server", @@ -42,6 +42,7 @@ "karma": "^0.13.22", "karma-chrome-launcher": "^0.2.3", "karma-cli": "^0.1.2", + "karma-htmlfile-reporter": "^0.2.2", "karma-jasmine": "^0.3.8", "live-server": "^0.9.2", "protractor": "^3.2.2", diff --git a/public/docs/_examples/protractor-conf.old.js b/public/docs/_examples/protractor-conf.old.js deleted file mode 100644 index 12dd89ab9f..0000000000 --- a/public/docs/_examples/protractor-conf.old.js +++ /dev/null @@ -1,24 +0,0 @@ -exports.config = { - onPrepare: function() { - patchProtractorWait(browser); - }, - seleniumAddress: 'http://localhost:4444/wd/hub', - baseUrl: 'http://localhost:8080/', - specs: [ - '**/*e2e-spec.js' - ] -}; - -// Disable waiting for Angular as we don't have an integration layer yet... -// TODO(tbosch): Implement a proper debugging API for Ng2.0, remove this here -// and the sleeps in all tests. -function patchProtractorWait(browser) { - browser.ignoreSynchronization = true; - var _get = browser.get; - var sleepInterval = process.env.TRAVIS || process.env.JENKINS_URL ? 14000 : 8000; - browser.get = function() { - var result = _get.apply(this, arguments); - browser.sleep(sleepInterval); - return result; - } -} diff --git a/public/docs/_examples/server-communication/ts/app/toh/hero.service.1.ts b/public/docs/_examples/server-communication/ts/app/toh/hero.service.1.ts index d5734fffc5..05b97fa75d 100644 --- a/public/docs/_examples/server-communication/ts/app/toh/hero.service.1.ts +++ b/public/docs/_examples/server-communication/ts/app/toh/hero.service.1.ts @@ -3,7 +3,7 @@ // #docregion import {Injectable} from 'angular2/core'; -import {Http, Response} from 'angular2/http'; +import {Http} from 'angular2/http'; import {Headers, RequestOptions} from 'angular2/http'; import {Hero} from './hero'; @@ -32,13 +32,13 @@ export class HeroService { .then(res => res.json().data) .catch(this.handleError); } - private handleError (error: any) { // in a real world app, we may send the error to some remote logging infrastructure - // instead of just logging it to the console - console.error(error); - return Promise.reject(error.message || error.json().error || 'Server error'); + console.error(error); // log to console instead + let errMsg = error.message || 'Server error'; + return Promise.reject(errMsg); } + // #enddocregion methods } // #enddocregion diff --git a/public/docs/_examples/server-communication/ts/app/toh/hero.service.ts b/public/docs/_examples/server-communication/ts/app/toh/hero.service.ts index 7ff9805ac0..4e9a0d9070 100644 --- a/public/docs/_examples/server-communication/ts/app/toh/hero.service.ts +++ b/public/docs/_examples/server-communication/ts/app/toh/hero.service.ts @@ -3,7 +3,7 @@ // #docregion // #docregion v1 import {Injectable} from 'angular2/core'; -import {Http, Response} from 'angular2/http'; +import {Http} from 'angular2/http'; // #enddocregion v1 // #docregion import-request-options import {Headers, RequestOptions} from 'angular2/http'; @@ -32,10 +32,10 @@ export class HeroService { // #docregion methods // #docregion error-handling - getHeroes () { + getHeroes (): Observable { // #docregion http-get, http-get-v1 return this.http.get(this._heroesUrl) - .map(res => res.json().data) + .map(this.extractData) // #enddocregion v1, http-get-v1, error-handling .do(data => console.log(data)) // eyeball results in the console // #docregion v1, http-get-v1, error-handling @@ -46,27 +46,36 @@ export class HeroService { // #enddocregion v1 // #docregion addhero - addHero (name: string) : Observable { + addHero (name: string): Observable { let body = JSON.stringify({ name }); - //#docregion headers + // #docregion headers let headers = new Headers({ 'Content-Type': 'application/json' }); let options = new RequestOptions({ headers: headers }); return this.http.post(this._heroesUrl, body, options) - //#enddocregion headers - .map(res => res.json().data) - .catch(this.handleError) + // #enddocregion headers + .map(this.extractData) + .catch(this.handleError); } // #enddocregion addhero // #docregion v1 + + private extractData(res: Response) { + if (res.status < 200 || res.status >= 300) { + throw new Error('Bad response status: ' + res.status); + } + let body = res.json(); + return body.data || { }; + } + // #docregion error-handling - private handleError (error: Response) { + private handleError (error: any) { // in a real world app, we may send the error to some remote logging infrastructure - // instead of just logging it to the console - console.error(error); - return Observable.throw(error.json().error || 'Server error'); + console.error(error); // log to console instead + let errMsg = error.message || 'Server error'; + return Observable.throw(errMsg); } // #enddocregion error-handling // #enddocregion methods diff --git a/public/docs/_examples/testing/ts/app/hero.ts b/public/docs/_examples/testing/ts/app/hero.ts index 2b89781da5..8f7cc205c8 100644 --- a/public/docs/_examples/testing/ts/app/hero.ts +++ b/public/docs/_examples/testing/ts/app/hero.ts @@ -1,5 +1,5 @@ // #docregion -export interface Hero { +export class Hero { id: number; name: string; } diff --git a/public/docs/_examples/testing/ts/app/http-hero.service.spec.ts b/public/docs/_examples/testing/ts/app/http-hero.service.spec.ts new file mode 100644 index 0000000000..f5d61b4955 --- /dev/null +++ b/public/docs/_examples/testing/ts/app/http-hero.service.spec.ts @@ -0,0 +1,148 @@ +/* tslint:disable:no-unused-variable */ +import { + it, + iit, + xit, + describe, + ddescribe, + xdescribe, + expect, + fakeAsync, + tick, + beforeEach, + inject, + injectAsync, + withProviders, + beforeEachProviders +} from 'angular2/testing'; + +import { provide } from 'angular2/core'; + +import { + MockBackend, + MockConnection } from 'angular2/src/http/backends/mock_backend'; + +import { + BaseRequestOptions, + ConnectionBackend, + Request, + RequestMethod, + RequestOptions, + Response, + ResponseOptions, + URLSearchParams, + HTTP_PROVIDERS, + XHRBackend, + Http} from 'angular2/http'; + +// Add all operators to Observable +import 'rxjs/Rx'; +import { Observable } from 'rxjs/Observable'; + +import { Hero } from './hero'; +import { HeroService } from './http-hero.service'; + +type HeroData = {id: string, name: string} + +const makeHeroData = () => [ + { "id": "1", "name": "Windstorm" }, + { "id": "2", "name": "Bombasto" }, + { "id": "3", "name": "Magneta" }, + { "id": "4", "name": "Tornado" } +]; + +// HeroService expects response data like {data: {the-data}} +const makeResponseData = (data: {}) => {return { data }; }; + +//////// SPECS ///////////// +describe('Http-HeroService (mockBackend)', () => { + + beforeEachProviders(() => [ + HTTP_PROVIDERS, + provide(XHRBackend, {useClass: MockBackend}) + ]); + + it('can instantiate service when inject service', + withProviders(() => [HeroService]) + .inject([HeroService], (service: HeroService) => { + expect(service instanceof HeroService).toBe(true); + })); + + + it('can instantiate service with "new"', inject([Http], (http: Http) => { + expect(http).not.toBeNull('http should be provided'); + let service = new HeroService(http); + expect(service instanceof HeroService).toBe(true, 'new service should be ok'); + })); + + + it('can provide the mockBackend as XHRBackend', + inject([XHRBackend], (backend: MockBackend) => { + expect(backend).not.toBeNull('backend should be provided'); + })); + + describe('when getHeroes', () => { + let backend: MockBackend; + let service: HeroService; + let fakeHeroes: HeroData[]; + let response: Response; + + + beforeEach(inject([Http, XHRBackend], (http: Http, be: MockBackend) => { + backend = be; + service = new HeroService(http); + fakeHeroes = makeHeroData(); + let options = new ResponseOptions({status: 200, body: {data: fakeHeroes}}); + response = new Response(options); + })); + + it('should have expected fake heroes (then)', injectAsync([], () => { + backend.connections.subscribe((c: MockConnection) => c.mockRespond(response)); + + return service.getHeroes().toPromise() + // .then(() => Promise.reject('deliberate')) + .then(heroes => { + expect(heroes.length).toEqual(fakeHeroes.length, + 'should have expected no. of heroes'); + }); + })); + + it('should have expected fake heroes (Observable.do)', injectAsync([], () => { + backend.connections.subscribe((c: MockConnection) => c.mockRespond(response)); + + return service.getHeroes() + .do(heroes => { + expect(heroes.length).toEqual(fakeHeroes.length, + 'should have expected no. of heroes'); + }) + .toPromise(); + })); + + + it('should be OK returning no heroes', injectAsync([], () => { + let resp = new Response(new ResponseOptions({status: 200, body: {data: []}})); + backend.connections.subscribe((c: MockConnection) => c.mockRespond(resp)); + + return service.getHeroes() + .do(heroes => { + expect(heroes.length).toEqual(0, 'should have no heroes'); + }) + .toPromise(); + })); + + it('should treat 404 as an Observable error', injectAsync([], () => { + let resp = new Response(new ResponseOptions({status: 404})); + backend.connections.subscribe((c: MockConnection) => c.mockRespond(resp)); + + return service.getHeroes() + .do(heroes => { + fail('should not respond with heroes'); + }) + .catch(err => { + expect(err).toMatch(/Bad response status/, 'should catch bad response status code'); + return Observable.of(null); // failure is the expected test result + }) + .toPromise(); + })); + }); +}); diff --git a/public/docs/_examples/testing/ts/app/http-hero.service.ts b/public/docs/_examples/testing/ts/app/http-hero.service.ts new file mode 100644 index 0000000000..40c2f37866 --- /dev/null +++ b/public/docs/_examples/testing/ts/app/http-hero.service.ts @@ -0,0 +1,44 @@ +// #docplaster +// #docregion +import {Injectable} from 'angular2/core'; +import {Http, Response} from 'angular2/http'; +import {Headers, RequestOptions} from 'angular2/http'; +import {Hero} from './hero'; +import {Observable} from 'rxjs/Observable'; + +@Injectable() +export class HeroService { + constructor (private http: Http) {} + private _heroesUrl = 'app/heroes'; // URL to web api + getHeroes (): Observable { + return this.http.get(this._heroesUrl) + .map(this.extractData) + // .do(data => console.log(data)) // eyeball results in the console + .catch(this.handleError); + } + + addHero (name: string): Observable { + let body = JSON.stringify({ name }); + let headers = new Headers({ 'Content-Type': 'application/json' }); + let options = new RequestOptions({ headers: headers }); + + return this.http.post(this._heroesUrl, body, options) + .map(this.extractData) + .catch(this.handleError); + } + + private extractData(res: Response) { + if (res.status < 200 || res.status >= 300) { + throw new Error('Bad response status: ' + res.status); + } + let body = res.json(); + return body.data || { }; + } + + private handleError (error: any) { + // in a real world app, we may send the error to some remote logging infrastructure + let errMsg = error.message || 'Server error'; + console.error(errMsg); // log to console instead + return Observable.throw(errMsg); + } +} diff --git a/public/docs/_examples/testing/ts/app/public-external-template.html b/public/docs/_examples/testing/ts/app/public-external-template.html new file mode 100644 index 0000000000..4c2b23755f --- /dev/null +++ b/public/docs/_examples/testing/ts/app/public-external-template.html @@ -0,0 +1 @@ +from external template diff --git a/public/docs/_examples/testing/ts/app/public.spec.ts b/public/docs/_examples/testing/ts/app/public.spec.ts new file mode 100644 index 0000000000..1ccd8c89f4 --- /dev/null +++ b/public/docs/_examples/testing/ts/app/public.spec.ts @@ -0,0 +1,458 @@ +// Based on https://github.com/angular/angular/blob/master/modules/angular2/test/testing/testing_public_spec.ts +/* tslint:disable:no-unused-variable */ +import { + BadTemplateUrl, ButtonComp, + ChildChildComp, ChildComp, ChildWithChildComp, + ExternalTemplateComp, + FancyService, MockFancyService, + MyIfComp, + MockChildComp, MockChildChildComp, + ParentComp, + TestProvidersComp, TestViewProvidersComp +} from './public'; + +import { + it, + iit, + xit, + describe, + ddescribe, + xdescribe, + expect, + fakeAsync, + tick, + beforeEach, + inject, + injectAsync, + withProviders, + beforeEachProviders, + TestComponentBuilder +} from 'angular2/testing'; + +import { provide } from 'angular2/core'; +import { ViewMetadata } from 'angular2/core'; +import { PromiseWrapper } from 'angular2/src/facade/promise'; +import { XHR } from 'angular2/src/compiler/xhr'; +import { XHRImpl } from 'angular2/src/platform/browser/xhr_impl'; + +/////////// Module Preparation /////////////////////// +interface Done { + (): void; + fail: (err: any) => void; +} + +//////// SPECS ///////////// + +/// Verify can use Angular testing's DOM abstraction to access DOM + +describe('angular2 jasmine matchers', () => { + describe('toHaveCssClass', () => { + it('should assert that the CSS class is present', () => { + let el = document.createElement('div'); + el.classList.add('matias'); + expect(el).toHaveCssClass('matias'); + }); + + it('should assert that the CSS class is not present', () => { + let el = document.createElement('div'); + el.classList.add('matias'); + expect(el).not.toHaveCssClass('fatias'); + }); + }); + + describe('toHaveCssStyle', () => { + it('should assert that the CSS style is present', () => { + let el = document.createElement('div'); + expect(el).not.toHaveCssStyle('width'); + + el.style.setProperty('width', '100px'); + expect(el).toHaveCssStyle('width'); + }); + + it('should assert that the styles are matched against the element', () => { + let el = document.createElement('div'); + expect(el).not.toHaveCssStyle({width: '100px', height: '555px'}); + + el.style.setProperty('width', '100px'); + expect(el).toHaveCssStyle({width: '100px'}); + expect(el).not.toHaveCssStyle({width: '100px', height: '555px'}); + + el.style.setProperty('height', '555px'); + expect(el).toHaveCssStyle({height: '555px'}); + expect(el).toHaveCssStyle({width: '100px', height: '555px'}); + }); + }); +}); + +describe('using the test injector with the inject helper', () => { + it('should run normal tests', () => { expect(true).toEqual(true); }); + + it('should run normal async tests', (done: Done) => { + setTimeout(() => { + expect(true).toEqual(true); + done(); + }, 0); + }); + + it('provides a real XHR instance', + inject([XHR], (xhr: any) => { expect(xhr).toBeAnInstanceOf(XHRImpl); })); + + describe('setting up Providers with FancyService', () => { + beforeEachProviders(() => [ + provide(FancyService, {useValue: new FancyService()}) + ]); + + it('should use FancyService', + inject([FancyService], (service: FancyService) => { + expect(service.value).toEqual('real value'); + })); + + it('test should wait for FancyService.getAsyncValue', + injectAsync([FancyService], (service: FancyService) => { + return service.getAsyncValue().then( + (value) => { expect(value).toEqual('async value'); }); + })); + + // Experimental: write async tests synchonously by faking async processing + it('should allow the use of fakeAsync (Experimental)', + inject([FancyService], fakeAsync((service: FancyService) => { + let value: any; + service.getAsyncValue().then((val: any) => value = val); + tick(); // Trigger JS engine cycle until all promises resolve. + expect(value).toEqual('async value'); + }))); + + describe('using inner beforeEach to inject-and-modify FancyService', () => { + beforeEach(inject([FancyService], (service: FancyService) => { + service.value = 'value modified in beforeEach'; + })); + + it('should use modified providers', + inject([FancyService], (service: FancyService) => { + expect(service.value).toEqual('value modified in beforeEach'); + })); + }); + + describe('using async within beforeEach', () => { + beforeEach(injectAsync([FancyService], (service: FancyService) => { + return service.getAsyncValue().then(value => { service.value = value; }); + })); + + it('should use asynchronously modified value ... in synchronous test', + inject([FancyService], (service: FancyService) => { + expect(service.value).toEqual('async value'); })); + }); + }); + + describe('using `withProviders` for per-test provision', () => { + it('should inject test-local FancyService for this test', + // `withProviders`: set up providers at individual test level + withProviders(() => [provide(FancyService, {useValue: {value: 'fake value'}})]) + + // now inject and test + .inject([FancyService], (service: FancyService) => { + expect(service.value).toEqual('fake value'); + })); + }); +}); + +describe('test component builder', function() { + it('should instantiate a component with valid DOM', + injectAsync([TestComponentBuilder], (tcb: TestComponentBuilder) => { + + return tcb.createAsync(ChildComp).then(fixture => { + fixture.detectChanges(); + expect(fixture.nativeElement).toHaveText('Original Child'); + }); + })); + + it('should allow changing members of the component', + injectAsync([TestComponentBuilder], (tcb: TestComponentBuilder) => { + + return tcb.createAsync(MyIfComp).then(fixture => { + fixture.detectChanges(); + expect(fixture.nativeElement).toHaveText('MyIf()'); + + fixture.debugElement.componentInstance.showMore = true; + fixture.detectChanges(); + expect(fixture.nativeElement).toHaveText('MyIf(More)'); + }); + })); + + it('should support clicking a button', + injectAsync([TestComponentBuilder], (tcb: TestComponentBuilder) => { + + return tcb.createAsync(ButtonComp).then(fixture => { + + let comp = fixture.componentInstance; + expect(comp.wasClicked).toEqual(false, 'wasClicked should be false at start'); + + let btn = fixture.debugElement.query(el => el.name === 'button'); + btn.triggerEventHandler('click', null); + // btn.nativeElement.click(); // this works too; which is "better"? + expect(comp.wasClicked).toEqual(true, 'wasClicked should be true after click'); + }); + })); + + it('should override a template', + injectAsync([TestComponentBuilder], (tcb: TestComponentBuilder) => { + + return tcb.overrideTemplate(MockChildComp, 'Mock') + .createAsync(MockChildComp) + .then(fixture => { + fixture.detectChanges(); + expect(fixture.nativeElement).toHaveText('Mock'); + }); + })); + + it('should override a view', + injectAsync([TestComponentBuilder], (tcb: TestComponentBuilder) => { + + return tcb.overrideView( + ChildComp, + new ViewMetadata({template: 'Modified {{childBinding}}'}) + ) + .createAsync(ChildComp) + .then(fixture => { + fixture.detectChanges(); + expect(fixture.nativeElement).toHaveText('Modified Child'); + + }); + })); + + it('should override component dependencies', + injectAsync([TestComponentBuilder], (tcb: TestComponentBuilder) => { + + return tcb.overrideDirective(ParentComp, ChildComp, MockChildComp) + .createAsync(ParentComp) + .then(fixture => { + fixture.detectChanges(); + expect(fixture.nativeElement).toHaveText('Parent(Mock)'); + + }); + })); + + + it('should override child component\'s dependencies', + injectAsync([TestComponentBuilder], (tcb: TestComponentBuilder) => { + + return tcb.overrideDirective(ParentComp, ChildComp, ChildWithChildComp) + .overrideDirective(ChildWithChildComp, ChildChildComp, MockChildChildComp) + .createAsync(ParentComp) + .then(fixture => { + fixture.detectChanges(); + expect(fixture.nativeElement) + .toHaveText('Parent(Original Child(ChildChild Mock))'); + + }); + })); + + it('should override a provider', + injectAsync([TestComponentBuilder], (tcb: TestComponentBuilder) => { + + return tcb.overrideProviders( + TestProvidersComp, + [provide(FancyService, {useClass: MockFancyService})] + ) + .createAsync(TestProvidersComp) + .then(fixture => { + fixture.detectChanges(); + expect(fixture.nativeElement) + .toHaveText('injected value: mocked out value'); + }); + })); + + + it('should override a viewProvider', + injectAsync([TestComponentBuilder], (tcb: TestComponentBuilder) => { + + return tcb.overrideViewProviders( + TestViewProvidersComp, + [provide(FancyService, {useClass: MockFancyService})] + ) + .createAsync(TestViewProvidersComp) + .then(fixture => { + fixture.detectChanges(); + expect(fixture.nativeElement) + .toHaveText('injected value: mocked out value'); + }); + })); + + it('should allow an external templateUrl', + injectAsync([TestComponentBuilder], (tcb: TestComponentBuilder) => { + + return tcb.createAsync(ExternalTemplateComp) + .then(fixture => { + fixture.detectChanges(); + expect(fixture.nativeElement) + .toHaveText('from external template\n'); + }); + }), 10000); // Long timeout because this test makes an actual XHR. +}); + +describe('errors', () => { + let originalJasmineIt: any; + let originalJasmineBeforeEach: any; + + let patchJasmineIt = () => { + let deferred = PromiseWrapper.completer(); + originalJasmineIt = jasmine.getEnv().it; + jasmine.getEnv().it = (description: string, fn: Function) => { + let done = () => { deferred.resolve(); }; + (done).fail = (err: any) => { deferred.reject(err); }; + fn(done); + return null; + }; + return deferred.promise; + }; + + let restoreJasmineIt = () => { jasmine.getEnv().it = originalJasmineIt; }; + + let patchJasmineBeforeEach = () => { + let deferred = PromiseWrapper.completer(); + originalJasmineBeforeEach = jasmine.getEnv().beforeEach; + jasmine.getEnv().beforeEach = (fn: any) => { + let done = () => { deferred.resolve(); }; + (done).fail = (err: any) => { deferred.reject(err); }; + fn(done); + return null; + }; + return deferred.promise; + }; + + let restoreJasmineBeforeEach = + () => { jasmine.getEnv().beforeEach = originalJasmineBeforeEach; }; + + const shouldNotSucceed = + (done: Done) => () => done.fail( 'Expected function to throw, but it did not'); + + const shouldFail = + (done: Done, emsg: string) => (err: any) => { expect(err).toEqual(emsg); done(); }; + + it('injectAsync should fail when return was forgotten in it', (done: Done) => { + let itPromise = patchJasmineIt(); + it('forgets to return a proimse', injectAsync([], () => { return true; })); + + itPromise.then( + shouldNotSucceed(done), + shouldFail(done, + 'Error: injectAsync was expected to return a promise, but the returned value was: true') + ); + restoreJasmineIt(); + }); + + it('inject should fail if a value was returned', (done: Done) => { + let itPromise = patchJasmineIt(); + it('returns a value', inject([], () => { return true; })); + + itPromise.then( + shouldNotSucceed(done), + shouldFail(done, + 'Error: inject returned a value. Did you mean to use injectAsync? Returned value was: true') + ); + restoreJasmineIt(); + }); + + it('injectAsync should fail when return was forgotten in beforeEach', (done: Done) => { + let beforeEachPromise = patchJasmineBeforeEach(); + beforeEach(injectAsync([], () => { return true; })); + + beforeEachPromise.then( + shouldNotSucceed(done), + shouldFail(done, + 'Error: injectAsync was expected to return a promise, but the returned value was: true') + ); + restoreJasmineBeforeEach(); + }); + + it('inject should fail if a value was returned in beforeEach', (done: Done) => { + let beforeEachPromise = patchJasmineBeforeEach(); + beforeEach(inject([], () => { return true; })); + + beforeEachPromise.then( + shouldNotSucceed(done), + shouldFail(done, + 'Error: inject returned a value. Did you mean to use injectAsync? Returned value was: true') + ); + restoreJasmineBeforeEach(); + }); + + it('should fail when an error occurs inside inject', (done: Done) => { + let itPromise = patchJasmineIt(); + + it('throws an error', inject([], () => { throw new Error('foo'); })); + + itPromise.then( + shouldNotSucceed(done), + err => { expect(err.message).toEqual('foo'); done(); } + ); + restoreJasmineIt(); + }); + + // TODO(juliemr): reenable this test when we are using a test zone and can capture this error. + xit('should fail when an asynchronous error is thrown', (done: Done) => { + let itPromise = patchJasmineIt(); + + it('throws an async error', + injectAsync([], () => { setTimeout(() => { throw new Error('bar'); }, 0); })); + + itPromise.then( + shouldNotSucceed(done), + err => { expect(err.message).toEqual('bar'); done(); } + ); + restoreJasmineIt(); + }); + + it('should fail when a returned promise is rejected', (done: Done) => { + let itPromise = patchJasmineIt(); + + it('should fail with an error from a promise', injectAsync([], () => { + let deferred = PromiseWrapper.completer(); + let p = deferred.promise.then(() => { expect(1).toEqual(2); }); + + deferred.reject('baz'); + return p; + })); + + itPromise.then( + shouldNotSucceed(done), + shouldFail(done, 'baz') + ); + restoreJasmineIt(); + }); + + it('should fail when an XHR fails', (done: Done) => { + let itPromise = patchJasmineIt(); + + it('should fail with an error from a promise', + injectAsync([TestComponentBuilder], (tcb: TestComponentBuilder) => { + return tcb.createAsync(BadTemplateUrl); + })); + + itPromise.then( + shouldNotSucceed(done), + shouldFail(done, 'Failed to load non-existant.html') + ); + restoreJasmineIt(); + }, 10000); + + describe('using beforeEachProviders', () => { + beforeEachProviders(() => [provide(FancyService, {useValue: new FancyService()})]); + + beforeEach( + inject([FancyService], (service: FancyService) => { expect(service.value).toEqual('real value'); })); + + describe('nested beforeEachProviders', () => { + + it('should fail when the injector has already been used', () => { + patchJasmineBeforeEach(); + expect(() => { + beforeEachProviders(() => [provide(FancyService, {useValue: new FancyService()})]); + }) + .toThrowError('beforeEachProviders was called after the injector had been used ' + + 'in a beforeEach or it block. This invalidates the test injector'); + restoreJasmineBeforeEach(); + }); + }); + }); +}); diff --git a/public/docs/_examples/testing/ts/app/public.ts b/public/docs/_examples/testing/ts/app/public.ts new file mode 100644 index 0000000000..382c2c700e --- /dev/null +++ b/public/docs/_examples/testing/ts/app/public.ts @@ -0,0 +1,133 @@ +// Based on https://github.com/angular/angular/blob/master/modules/angular2/test/testing/testing_public_spec.ts +import { Component, Injectable } from 'angular2/core'; +import { NgIf } from 'angular2/common'; + +// Let TypeScript know about the special SystemJS __moduleName variable +declare var __moduleName: string; + +// moduleName is not set in some module loaders; set it explicitly +if (!__moduleName) { + __moduleName = `http://${location.host}/${location.pathname}/app/`; +} +// console.log(`The __moduleName is ${__moduleName} `); + + + +////////// The App: Services and Components for the tests. ////////////// + +////////// Services /////////////// + +@Injectable() +export class FancyService { + value: string = 'real value'; + getAsyncValue() { return Promise.resolve('async value'); } +} + +@Injectable() +export class MockFancyService extends FancyService { + value: string = 'mocked out value'; +} + +//////////// Components ///////////// + +@Component({ + selector: 'button-comp', + template: `` +}) +export class ButtonComp { + wasClicked = false; + clicked() { this.wasClicked = true; } +} + + +@Component({ + selector: 'child-comp', + template: `Original {{childBinding}}` +}) +export class ChildComp { + childBinding = 'Child'; +} + + +@Component({ + selector: 'child-comp', + template: `Mock` +}) +export class MockChildComp { } + + +@Component({ + selector: 'parent-comp', + template: `Parent()`, + directives: [ChildComp] +}) +export class ParentComp { } + + +@Component({ + selector: 'my-if-comp', + template: `MyIf(More)`, + directives: [NgIf] +}) +export class MyIfComp { + showMore: boolean = false; +} + + +@Component({ + selector: 'child-child-comp', + template: 'ChildChild' +}) +export class ChildChildComp { } + + +@Component({ + selector: 'child-comp', + template: `Original {{childBinding}}()`, + directives: [ChildChildComp] +}) +export class ChildWithChildComp { + childBinding = 'Child'; +} + + +@Component({ + selector: 'child-child-comp', + template: `ChildChild Mock` +}) +export class MockChildChildComp { } + + +@Component({ + selector: 'my-service-comp', + template: `injected value: {{fancyService.value}}`, + providers: [FancyService] +}) +export class TestProvidersComp { + constructor(private fancyService: FancyService) {} +} + + +@Component({ + selector: 'my-service-comp', + template: `injected value: {{fancyService.value}}`, + viewProviders: [FancyService] +}) +export class TestViewProvidersComp { + constructor(private fancyService: FancyService) {} +} + + +@Component({ + moduleId: __moduleName, + selector: 'external-template-comp', + templateUrl: 'public-external-template.html' +}) +export class ExternalTemplateComp { } + + +@Component({ + selector: 'bad-template-comp', + templateUrl: 'non-existant.html' +}) +export class BadTemplateUrl { } diff --git a/public/docs/_examples/testing/ts/test-shim.js b/public/docs/_examples/testing/ts/test-shim.js new file mode 100644 index 0000000000..31e1998e69 --- /dev/null +++ b/public/docs/_examples/testing/ts/test-shim.js @@ -0,0 +1,48 @@ +/*global jasmine, __karma__, window*/ + +// Browser testing shim +(function () { + +// Error.stackTraceLimit = Infinity; + +jasmine.DEFAULT_TIMEOUT_INTERVAL = 1000; + +// Configure systemjs to use the .js extension for imports from the app folder +System.config({ + packages: { + app: { + format: 'register', + defaultExtension: 'js' + } + } +}); + +// Configure Angular for the browser and with test versions of the platform providers +System.import('angular2/testing') + .then(function (testing) { + return System.import('angular2/platform/testing/browser') + .then(function (providers) { + testing.setBaseTestProviders( + providers.TEST_BROWSER_PLATFORM_PROVIDERS, + providers.TEST_BROWSER_APPLICATION_PROVIDERS + ); + }); + }) + + // Load the spec files (__spec_files__) explicitly + .then(function () { + console.log('loading spec files: '+__spec_files__.join(', ')); + return Promise.all(__spec_files__.map(function(spec) { return System.import(spec);} )); + }) + + // After all imports load, re-execute `window.onload` which + // triggers the Jasmine test-runner start or explain what went wrong + .then(success, console.error.bind(console)); + +function success () { + console.log('Spec files loaded; starting Jasmine testrunner'); + window.onload(); +} + + +})(); diff --git a/public/docs/_examples/testing/ts/unit-tests-public.html b/public/docs/_examples/testing/ts/unit-tests-public.html new file mode 100644 index 0000000000..cbb3f7f859 --- /dev/null +++ b/public/docs/_examples/testing/ts/unit-tests-public.html @@ -0,0 +1,32 @@ + + + + + + Angular Public Unit Tests + + + + + + + + + + + + + + + + + + + + + + + + From 353abff0841671eff35d3275987ba6b93d7bb35b Mon Sep 17 00:00:00 2001 From: Ward Bell Date: Wed, 13 Apr 2016 08:21:32 -0700 Subject: [PATCH 3/5] docs(server-communication): fix http after testing chapter discoveries --- .../server-communication/ts/app/main.ts | 18 ++- .../ts/app/toh/hero-list.component.1.ts | 20 +--- .../ts/app/toh/hero-list.component.html | 13 +++ .../ts/app/toh/hero-list.component.ts | 15 +-- .../ts/app/toh/hero.service.1.ts | 27 +++-- .../ts/app/toh/hero.service.ts | 17 ++- .../ts/app/toh/toh.component.1.ts | 32 ++++++ .../ts/app/toh/toh.component.2.ts | 44 ++++++++ .../ts/app/toh/toh.component.ts | 37 +++--- .../testing/ts/app/http-hero.service.ts | 2 +- .../ts/latest/guide/server-communication.jade | 105 +++++++++++------- .../server-communication/hero-list.png | Bin 24050 -> 12153 bytes 12 files changed, 213 insertions(+), 117 deletions(-) create mode 100644 public/docs/_examples/server-communication/ts/app/toh/hero-list.component.html create mode 100644 public/docs/_examples/server-communication/ts/app/toh/toh.component.1.ts create mode 100644 public/docs/_examples/server-communication/ts/app/toh/toh.component.2.ts diff --git a/public/docs/_examples/server-communication/ts/app/main.ts b/public/docs/_examples/server-communication/ts/app/main.ts index c992809065..a7c4bab464 100644 --- a/public/docs/_examples/server-communication/ts/app/main.ts +++ b/public/docs/_examples/server-communication/ts/app/main.ts @@ -1,15 +1,21 @@ -//#docregion -import {bootstrap} from 'angular2/platform/browser'; +// #docplaster +// #docregion +import { bootstrap } from 'angular2/platform/browser'; +// #docregion http-providers +import { HTTP_PROVIDERS } from 'angular2/http'; +// #enddocregion http-providers // #docregion import-rxjs // Add all operators to Observable import 'rxjs/Rx'; // #enddocregion import-rxjs -import {WikiComponent} from './wiki/wiki.component'; -import {WikiSmartComponent} from './wiki/wiki-smart.component'; -import {TohComponent} from './toh/toh.component'; +import { WikiComponent } from './wiki/wiki.component'; +import { WikiSmartComponent } from './wiki/wiki-smart.component'; +import { TohComponent } from './toh/toh.component'; bootstrap(WikiComponent); bootstrap(WikiSmartComponent); -bootstrap(TohComponent); \ No newline at end of file +// #docregion http-providers +bootstrap(TohComponent, [HTTP_PROVIDERS]); +// #enddocregion http-providers diff --git a/public/docs/_examples/server-communication/ts/app/toh/hero-list.component.1.ts b/public/docs/_examples/server-communication/ts/app/toh/hero-list.component.1.ts index 2a96ce2df3..4506bab39f 100644 --- a/public/docs/_examples/server-communication/ts/app/toh/hero-list.component.1.ts +++ b/public/docs/_examples/server-communication/ts/app/toh/hero-list.component.1.ts @@ -1,3 +1,4 @@ +// ToH Promise Version // #docregion import {Component, OnInit} from 'angular2/core'; import {Hero} from './hero'; @@ -5,22 +6,7 @@ import {HeroService} from './hero.service.1'; @Component({ selector: 'hero-list', -// #docregion template - template: ` -

Heroes:

-
    -
  • - {{ hero.name }} -
  • -
- New Hero: - - -
{{errorMessage}}
- `, - // #enddocregion template + templateUrl: 'app/toh/hero-list.component.html', styles: ['.error {color:red;}'] }) // #docregion component @@ -29,7 +15,7 @@ export class HeroListComponent implements OnInit { constructor (private _heroService: HeroService) {} errorMessage: string; - heroes:Hero[]; + heroes: Hero[]; ngOnInit() { this.getHeroes(); } diff --git a/public/docs/_examples/server-communication/ts/app/toh/hero-list.component.html b/public/docs/_examples/server-communication/ts/app/toh/hero-list.component.html new file mode 100644 index 0000000000..22105a6b15 --- /dev/null +++ b/public/docs/_examples/server-communication/ts/app/toh/hero-list.component.html @@ -0,0 +1,13 @@ + +

Heroes:

+
    +
  • + {{ hero.name }} +
  • +
+New Hero: + + +
{{errorMessage}}
diff --git a/public/docs/_examples/server-communication/ts/app/toh/hero-list.component.ts b/public/docs/_examples/server-communication/ts/app/toh/hero-list.component.ts index a55cf35a72..088ffc56a6 100644 --- a/public/docs/_examples/server-communication/ts/app/toh/hero-list.component.ts +++ b/public/docs/_examples/server-communication/ts/app/toh/hero-list.component.ts @@ -5,20 +5,7 @@ import {HeroService} from './hero.service'; @Component({ selector: 'hero-list', - template: ` -

Heroes:

-
    -
  • - {{ hero.name }} -
  • -
- New Hero: - - -
{{errorMessage}}
- `, + templateUrl: 'app/toh/hero-list.component.html', styles: ['.error {color:red;}'] }) // #docregion component diff --git a/public/docs/_examples/server-communication/ts/app/toh/hero.service.1.ts b/public/docs/_examples/server-communication/ts/app/toh/hero.service.1.ts index 05b97fa75d..8ac1d92a2c 100644 --- a/public/docs/_examples/server-communication/ts/app/toh/hero.service.1.ts +++ b/public/docs/_examples/server-communication/ts/app/toh/hero.service.1.ts @@ -1,9 +1,9 @@ -/* Promise version */ +// ToH Promise Version // #docplaster // #docregion import {Injectable} from 'angular2/core'; -import {Http} from 'angular2/http'; +import {Http, Response} from 'angular2/http'; import {Headers, RequestOptions} from 'angular2/http'; import {Hero} from './hero'; @@ -15,27 +15,36 @@ export class HeroService { private _heroesUrl = 'app/heroes.json'; // #docregion methods - getHeroes () { + getHeroes (): Promise { return this.http.get(this._heroesUrl) .toPromise() - .then(res => res.json().data, this.handleError) - .then(data => { console.log(data); return data; }); // eyeball results in the console + .then(this.extractData) + .catch(this.handleError); } - addHero (name: string) : Promise { + addHero (name: string): Promise { let body = JSON.stringify({ name }); let headers = new Headers({ 'Content-Type': 'application/json' }); let options = new RequestOptions({ headers: headers }); return this.http.post(this._heroesUrl, body, options) .toPromise() - .then(res => res.json().data) + .then(this.extractData) .catch(this.handleError); } + + private extractData(res: Response) { + if (res.status < 200 || res.status >= 300) { + throw new Error('Bad response status: ' + res.status); + } + let body = res.json(); + return body.data || { }; + } + private handleError (error: any) { - // in a real world app, we may send the error to some remote logging infrastructure - console.error(error); // log to console instead + // In a real world app, we might send the error to remote logging infrastructure let errMsg = error.message || 'Server error'; + console.error(errMsg); // log to console instead return Promise.reject(errMsg); } diff --git a/public/docs/_examples/server-communication/ts/app/toh/hero.service.ts b/public/docs/_examples/server-communication/ts/app/toh/hero.service.ts index 4e9a0d9070..0ada9137fc 100644 --- a/public/docs/_examples/server-communication/ts/app/toh/hero.service.ts +++ b/public/docs/_examples/server-communication/ts/app/toh/hero.service.ts @@ -3,7 +3,7 @@ // #docregion // #docregion v1 import {Injectable} from 'angular2/core'; -import {Http} from 'angular2/http'; +import {Http, Response} from 'angular2/http'; // #enddocregion v1 // #docregion import-request-options import {Headers, RequestOptions} from 'angular2/http'; @@ -31,18 +31,13 @@ export class HeroService { // #enddocregion endpoint // #docregion methods - // #docregion error-handling + // #docregion error-handling, http-get getHeroes (): Observable { - // #docregion http-get, http-get-v1 return this.http.get(this._heroesUrl) .map(this.extractData) - // #enddocregion v1, http-get-v1, error-handling - .do(data => console.log(data)) // eyeball results in the console - // #docregion v1, http-get-v1, error-handling .catch(this.handleError); - // #enddocregion http-get, http-get-v1 } - // #enddocregion error-handling + // #enddocregion error-handling, http-get // #enddocregion v1 // #docregion addhero @@ -62,6 +57,7 @@ export class HeroService { // #docregion v1 + // #docregion extract-data private extractData(res: Response) { if (res.status < 200 || res.status >= 300) { throw new Error('Bad response status: ' + res.status); @@ -69,12 +65,13 @@ export class HeroService { let body = res.json(); return body.data || { }; } + // #enddocregion extract-data // #docregion error-handling private handleError (error: any) { - // in a real world app, we may send the error to some remote logging infrastructure - console.error(error); // log to console instead + // In a real world app, we might send the error to remote logging infrastructure let errMsg = error.message || 'Server error'; + console.error(errMsg); // log to console instead return Observable.throw(errMsg); } // #enddocregion error-handling diff --git a/public/docs/_examples/server-communication/ts/app/toh/toh.component.1.ts b/public/docs/_examples/server-communication/ts/app/toh/toh.component.1.ts new file mode 100644 index 0000000000..d689f73fd3 --- /dev/null +++ b/public/docs/_examples/server-communication/ts/app/toh/toh.component.1.ts @@ -0,0 +1,32 @@ +// ToH Promise Version +console.log ('Promise version'); + +import { Component } from 'angular2/core'; +import { HTTP_PROVIDERS } from 'angular2/http'; + +import { HeroListComponent } from './hero-list.component.1'; +import { HeroService } from './hero.service.1'; + +import { provide } from 'angular2/core'; +import { XHRBackend } from 'angular2/http'; + +import { InMemoryBackendService, + SEED_DATA } from 'a2-in-memory-web-api/core'; +import { HeroData } from '../hero-data'; + +@Component({ + selector: 'my-toh', + template: ` +

Tour of Heroes

+ + `, + directives:[HeroListComponent], + providers: [ + HTTP_PROVIDERS, + HeroService, + // in-memory web api providers + provide(XHRBackend, { useClass: InMemoryBackendService }), // in-mem server + provide(SEED_DATA, { useClass: HeroData }) // in-mem server data + ] +}) +export class TohComponent { } diff --git a/public/docs/_examples/server-communication/ts/app/toh/toh.component.2.ts b/public/docs/_examples/server-communication/ts/app/toh/toh.component.2.ts new file mode 100644 index 0000000000..f6efb282a5 --- /dev/null +++ b/public/docs/_examples/server-communication/ts/app/toh/toh.component.2.ts @@ -0,0 +1,44 @@ +// #docplaster + +// #docregion +import { Component } from 'angular2/core'; +import { HTTP_PROVIDERS } from 'angular2/http'; + +import { HeroListComponent } from './hero-list.component'; +import { HeroService } from './hero.service'; +// #enddocregion + +// #docregion in-mem-web-api-imports +import { provide } from 'angular2/core'; +import { XHRBackend } from 'angular2/http'; + +// in-memory web api imports +import { InMemoryBackendService, + SEED_DATA } from 'a2-in-memory-web-api/core'; +import { HeroData } from '../hero-data'; +// #enddocregion in-mem-web-api-imports +// #docregion + +@Component({ + selector: 'my-toh', +// #docregion template + template: ` +

Tour of Heroes

+ + `, + // #enddocregion template + directives: [HeroListComponent], + providers: [ + HTTP_PROVIDERS, + HeroService, +// #enddocregion +// #docregion in-mem-web-api-providers + // in-memory web api providers + provide(XHRBackend, { useClass: InMemoryBackendService }), // in-mem server + provide(SEED_DATA, { useClass: HeroData }) // in-mem server data +// #enddocregion in-mem-web-api-providers +// #docregion + ] +}) +export class TohComponent { } +// #enddocregion diff --git a/public/docs/_examples/server-communication/ts/app/toh/toh.component.ts b/public/docs/_examples/server-communication/ts/app/toh/toh.component.ts index bc93e5c9c9..f6efb282a5 100644 --- a/public/docs/_examples/server-communication/ts/app/toh/toh.component.ts +++ b/public/docs/_examples/server-communication/ts/app/toh/toh.component.ts @@ -1,24 +1,23 @@ // #docplaster // #docregion -import {Component} from 'angular2/core'; -import {HTTP_PROVIDERS} from 'angular2/http'; +import { Component } from 'angular2/core'; +import { HTTP_PROVIDERS } from 'angular2/http'; -import {Hero} from './hero'; -import {HeroListComponent} from './hero-list.component'; -import {HeroService} from './hero.service'; -//#enddocregion +import { HeroListComponent } from './hero-list.component'; +import { HeroService } from './hero.service'; +// #enddocregion -//#docregion in-mem-web-api-imports -import {provide} from 'angular2/core'; -import {XHRBackend} from 'angular2/http'; +// #docregion in-mem-web-api-imports +import { provide } from 'angular2/core'; +import { XHRBackend } from 'angular2/http'; // in-memory web api imports -import {InMemoryBackendService, - SEED_DATA} from 'a2-in-memory-web-api/core'; -import {HeroData} from '../hero-data'; +import { InMemoryBackendService, + SEED_DATA } from 'a2-in-memory-web-api/core'; +import { HeroData } from '../hero-data'; // #enddocregion in-mem-web-api-imports -//#docregion +// #docregion @Component({ selector: 'my-toh', @@ -28,17 +27,17 @@ import {HeroData} from '../hero-data'; `, // #enddocregion template - directives:[HeroListComponent], - providers: [ + directives: [HeroListComponent], + providers: [ HTTP_PROVIDERS, HeroService, -//#enddocregion -//#docregion in-mem-web-api-providers +// #enddocregion +// #docregion in-mem-web-api-providers // in-memory web api providers provide(XHRBackend, { useClass: InMemoryBackendService }), // in-mem server provide(SEED_DATA, { useClass: HeroData }) // in-mem server data -//#enddocregion in-mem-web-api-providers -//#docregion +// #enddocregion in-mem-web-api-providers +// #docregion ] }) export class TohComponent { } diff --git a/public/docs/_examples/testing/ts/app/http-hero.service.ts b/public/docs/_examples/testing/ts/app/http-hero.service.ts index 40c2f37866..86f3dcf8d2 100644 --- a/public/docs/_examples/testing/ts/app/http-hero.service.ts +++ b/public/docs/_examples/testing/ts/app/http-hero.service.ts @@ -36,7 +36,7 @@ export class HeroService { } private handleError (error: any) { - // in a real world app, we may send the error to some remote logging infrastructure + // In a real world app, we might send the error to remote logging infrastructure let errMsg = error.message || 'Server error'; console.error(errMsg); // log to console instead return Observable.throw(errMsg); diff --git a/public/docs/ts/latest/guide/server-communication.jade b/public/docs/ts/latest/guide/server-communication.jade index eefc531262..248aa33c14 100644 --- a/public/docs/ts/latest/guide/server-communication.jade +++ b/public/docs/ts/latest/guide/server-communication.jade @@ -21,7 +21,6 @@ include ../_util-fns [Enabling RxJS Operators](#enable-rxjs-operators)
[Extract JSON data with RxJS map](#map)
[Error handling](#error-handling)
- [Log results to console](#do)
[Send data to the server](#update)
[Add headers](#headers)
[Promises instead of observables](#promises)
@@ -67,14 +66,20 @@ figure.image-display making them available to the child components of this "Tour of Heroes" application. .l-sub-section + :marked + Alternatively, we may choose to add the `HTTP_PROVIDERS` while bootstrapping the app: + +makeExample('server-communication/ts/app/main.ts','http-providers','app/main.ts')(format='.') :marked Learn about providers in the [Dependency Injection](dependency-injection.html) chapter. + :marked - This sample only has one child, the `HeroListComponent` shown here in full: -+makeExample('server-communication/ts/app/toh/hero-list.component.ts', null, 'app/toh/hero-list.component.ts') + This sample only has one child, the `HeroListComponent`. Here's its template: ++makeExample('server-communication/ts/app/toh/hero-list.component.html', null, 'app/toh/hero-list.component.html (Template)') :marked The component template displays a list of heroes with the `NgFor` repeater directive. - +figure.image-display + img(src='/resources/images/devguide/server-communication/hero-list.png' alt="Hero List") +:marked Beneath the heroes is an input box and an *Add Hero* button where we can enter the names of new heroes and add them to the database. We use a [local template variable](template-syntax.html#local-vars), `newHero`, to access the @@ -82,22 +87,26 @@ figure.image-display When the user clicks the button, we pass that value to the component's `addHero` method and then clear it to make ready for a new hero name. - Below the button is an optional error message. + Below the button is a (hidden) area for an error message. a(id="oninit") a(id="HeroListComponent") :marked ### The *HeroListComponent* class + Here's the component class: ++makeExample('server-communication/ts/app/toh/hero-list.component.ts','component', 'app/toh/hero-list.component.ts (class)') +:marked We [inject](dependency-injection.html) the `HeroService` into the constructor. That's the instance of the `HeroService` that we provided in the parent shell `TohComponent`. Notice that the component **does not talk to the server directly!** The component doesn't know or care how we get the data. Those details it delegates to the `heroService` class (which we'll get to in a moment). - This is a golden rule: *always delegate data access to a supporting service class*. + + This is a golden rule: **always delegate data access to a supporting service class**. - Although the component should request heroes immediately, - we do **not** call the service `get` method in the component's constructor. + Although _at runtime_ the component requests heroes immediately after creation, + we do **not** call the service's `get` method in the component's constructor. We call it inside the `ngOnInit` [lifecycle hook](lifecycle-hooks.html) instead and count on Angular to call `ngOnInit` when it instantiates this component. .l-sub-section @@ -106,8 +115,9 @@ a(id="HeroListComponent") Components are easier to test and debug when their constructors are simple and all real work (especially calling a remote server) is handled in a separate method. :marked - The service `get` and `addHero` methods return an `Observable` of HTTP Responses to which we `subscribe`, - specifying the actions to take if a method succeeds or fails. + The service `get` and `addHero` methods return an `Observable` of HTTP hero data. + We subscribe to this `Observable`, + specifying the actions to take when the request succeeds or fails. We'll get to observables and subscription shortly. With our basic intuitions about the component squared away, we can turn to development of the backend data source @@ -122,7 +132,7 @@ a(id="HeroListComponent") In this chapter, we get the heroes from the server using Angular's own HTTP Client service. Here's the new `HeroService`: -+makeExample('server-communication/ts/app/toh/hero.service.ts', 'v1', 'app/toh/hero.service.ts')(format=".") ++makeExample('server-communication/ts/app/toh/hero.service.ts', 'v1', 'app/toh/hero.service.ts') :marked We begin by importing Angular's `Http` client service and [inject it](dependency-injection.html) into the `HeroService` constructor. @@ -133,7 +143,7 @@ a(id="HeroListComponent") +makeExample('server-communication/ts/index.html', 'http', 'index.html')(format=".") :marked Look closely at how we call `http.get` -+makeExample('server-communication/ts/app/toh/hero.service.ts', 'http-get-v1', 'app/toh/hero.service.ts (http.get)')(format=".") ++makeExample('server-communication/ts/app/toh/hero.service.ts', 'http-get', 'app/toh/hero.service.ts (getHeroes)')(format=".") :marked We pass the resource URL to `get` and it calls the server which should return heroes. .l-sub-section @@ -153,13 +163,6 @@ a(id="HeroListComponent") In fact, the `http.get` method returns an **Observable** of HTTP Responses (`Observable`) from the RxJS library and `map` is one of the RxJS *operators*. -.callout.is-important - header HTTP GET Delayed - :marked - The `http.get` does **not send the request just yet!** This observable is - [*cold*](https://github.com/Reactive-Extensions/RxJS/blob/master/doc/gettingstarted/creating.md#cold-vs-hot-observables) - which means the request won't go out until something *subscribes* to the observable. - That *something* is the [HeroListComponent](#subscribe). .l-main-section :marked @@ -193,15 +196,37 @@ a(id="HeroListComponent") It's best to add that statement early when we're bootstrapping the application. : +makeExample('server-communication/ts/app/main.ts', 'import-rxjs', 'app/main.ts (import rxjs)')(format=".") + +a(id="map") +a(id="extract-data") :marked - - ### Map the response object - Let's come back to the `HeroService` and look at the `http.get` call again to see why we needed `map()` -+makeExample('server-communication/ts/app/toh/hero.service.ts', 'http-get-v1', 'app/toh/hero.service.ts (http.get)')(format=".") + ### Process the response object + Remember that our `getHeroes` method mapped the `http.get` response object to heroes with an `extractData` helper method: ++makeExample('server-communication/ts/app/toh/hero.service.ts', 'extract-data', 'app/toh/hero.service.ts (extractData)')(format=".") :marked The `response` object does not hold our data in a form we can use directly. - It takes an additional step — calling `response.json()` — to transform the bytes from the server into a JSON object. + To make it useful in our application we must + * check for a bad response + * parse the response data into a JSON object +.alert.is-important + :marked + *Beta alert*: error status interception and parsing may be absorbed within `http` when Angular is released. +:marked + #### Bad status codes + A status code outside the 200-300 range is an error from the _application point of view_ + but it is not an error from the _`http` point of view_. + For example, a `404 - Not Found` is a response like any other. + The request went out; a response came back; here it is, thank you very much. + We'd have an observable error only if `http` failed to operate (e.g., it errored internally). + + Because a status code outside the 200-300 range _is an error_ from the application point of view, + we intercept it and throw, moving the observable chain to the error path. + + The `catch` operator that is next in the `getHeroes` observable chain will handle our thrown error. + #### Parse to JSON + The response data are in JSON string form. + We must parse that string into JavaScript objects which we do by calling `response.json()`. .l-sub-section :marked This is not Angular's own design. @@ -228,8 +253,18 @@ a(id="HeroListComponent") It has no interest in what we do to get them. It doesn't care where they come from. And it certainly doesn't want to deal with a response object. + + +.callout.is-important + header HTTP GET is delayed + :marked + The `http.get` does **not send the request just yet!** This observable is + [*cold*](https://github.com/Reactive-Extensions/RxJS/blob/master/doc/gettingstarted/creating.md#cold-vs-hot-observables) + which means the request won't go out until something *subscribes* to the observable. + That *something* is the [HeroListComponent](#subscribe). - +a(id="error-handling") +:marked ### Always handle errors The eagle-eyed reader may have spotted our use of the `catch` operator in conjunction with a `handleError` method. @@ -243,8 +278,8 @@ a(id="HeroListComponent") In this simple app we provide rudimentary error handling in both the service and the component. We use the Observable `catch` operator on the service level. - It takes an error handling function with the failed `Response` object as the argument. - Our service handler, `errorHandler`, logs the response to the console, + It takes an error handling function with an error object as the argument. + Our service handler, `handleError`, logs the response to the console, transforms the error into a user-friendly message, and returns the message in a new, failed observable via `Observable.throw`. +makeExample('server-communication/ts/app/toh/hero.service.ts', 'error-handling', 'app/toh/hero.service.ts')(format=".") @@ -263,19 +298,7 @@ a(id="HeroListComponent") .l-sub-section :marked Want to see it fail? Reset the api endpoint in the `HeroService` to a bad value. Remember to restore it! - - -:marked - ### Peek at results in the console - During development we're often curious about the data returned by the server. - Logging to console without disrupting the flow would be nice. - - The Observable `do` operator is perfect for the job. - It passes the input through to the output while we do something with a useful side-effect such as writing to console. - Slip it into the pipeline between `map` and `catch` like this. -+makeExample('server-communication/ts/app/toh/hero.service.ts', 'http-get', 'app/toh/hero.service.ts')(format=".") -:marked - Remember to comment it out before going to production! + @@ -327,7 +350,7 @@ code-example(format="." language="javascript"). :marked ### JSON results - As with `get`, we extract the data from the response with `json()` and unwrap the hero via the `data` property. + As with `getHeroes`, we [extract the data](#extract-data) from the response with `json()` and unwrap the hero via the `data` property. .alert.is-important :marked Know the shape of the data returned by the server. diff --git a/public/resources/images/devguide/server-communication/hero-list.png b/public/resources/images/devguide/server-communication/hero-list.png index db53046c71095286be875493ff2ac791a22e9fb2..6d2169eaab7936e0c6830daa33b1420d8c51cfc0 100644 GIT binary patch literal 12153 zcmch-X*`vC_%5zVl(3~xBBe;CP-aS$%8*#4GGrbyPnqq?P$XNDDTGi<*ivM!kYpht zWF{oD70c{g&;EVR=l_3k-k$Sfx9hR2^{nr6-`9N&_x+1nXLoGdvyG09ZpS%w)k}1A z8?^EFSO$9hX@2`=6aL5Oq<+JEP3nPBQNc=?C(bDafiHilDq0>6?^6me$Nu-rPCMG$TR6DU%~PIK z;2J&gGCdnNI}5rOlivjB==Rf{Q$3~U`E;V&#*Uljw?0Fo^l%h)4V4+3KOoY{?tU>u zMCXyk(I<9CUw6xBnM%a5&odbCp)pQ+tWJ(=|8WWt;EDv!jf*V)$} zd#b;7uai^1P&#!}+oh;Pk{a-SQuXGgf;X?th1SaH4)#$dDULBsAr*_O{?vWd;!K0X z^$7+Q{)zPo(z@5Kec>1_*1CRuZ)obj7InK{T^_sB#=uuqc)wMgNon!tPXC!Oxh=ec>C?j{&$(K8&uPD{Fgg>zkUCHMu8_YHT90j^@8bd7sPb*^fptrI{Em>ci272 zzFufr*f}+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^8w^L*rDHrn>d16x>X6@f)Tyg>x7}+*ci%!#ZTyv2D2STH`#Jl zE@oIpWMyuv8lon~0a01vcQtovVHQCcC4aw?SXH%|D)2@@|@j{v@ zURo|xs^coY%ly^~9)CH{HK@z{n9Nzw)fIsBCK5*vq3y#<5*oT-`W+vKo??KZ_4K_S wn|gU<+IGbuK^^lSPMgX=67@fTHa=&Ty}#0+ygbi<)#heg-+jAvoTKS~0eHx4$N&HU From f2f5d9f9aecd5ee789657d7317581ff01d43d35d Mon Sep 17 00:00:00 2001 From: Ward Bell Date: Wed, 13 Apr 2016 19:07:20 -0700 Subject: [PATCH 4/5] docs(ts): update to beta.15 also restore accidentally deleted router sample files --- .../homepage-hello-world/ts/index.1.html | 8 +-- .../_examples/homepage-tabs/ts/index.1.html | 8 +-- .../_examples/homepage-todo/ts/index.1.html | 8 +-- public/docs/_examples/package.json | 10 ++-- .../_examples/quickstart/js/package.1.json | 4 +- .../_examples/quickstart/ts/package.1.json | 8 +-- .../_examples/quickstart/ts/typings.1.json | 2 +- .../_examples/router/ts/example-config.json | 0 public/docs/_examples/router/ts/index.html | 50 +++++++++++++++++++ public/docs/_examples/typings.json | 2 +- public/docs/dart/latest/_data.json | 2 +- public/docs/js/latest/_data.json | 2 +- public/docs/ts/latest/_data.json | 2 +- tools/plunker-builder/indexHtmlTranslator.js | 25 +++++----- 14 files changed, 91 insertions(+), 40 deletions(-) create mode 100644 public/docs/_examples/router/ts/example-config.json create mode 100644 public/docs/_examples/router/ts/index.html diff --git a/public/docs/_examples/homepage-hello-world/ts/index.1.html b/public/docs/_examples/homepage-hello-world/ts/index.1.html index 3b747789d7..c311e81341 100644 --- a/public/docs/_examples/homepage-hello-world/ts/index.1.html +++ b/public/docs/_examples/homepage-hello-world/ts/index.1.html @@ -9,14 +9,14 @@ - + - - - + + + - + - - - + + + - + - - - + + + + + + + + + + + + + + + + + + + + + + loading... + + + + diff --git a/public/docs/_examples/typings.json b/public/docs/_examples/typings.json index c06bb4d720..d6a258cfb6 100644 --- a/public/docs/_examples/typings.json +++ b/public/docs/_examples/typings.json @@ -1,6 +1,6 @@ { "ambientDependencies": { "es6-shim": "github:DefinitelyTyped/DefinitelyTyped/es6-shim/es6-shim.d.ts#7de6c3dd94feaeb21f20054b9f30d5dabc5efabd", - "jasmine": "github:DefinitelyTyped/DefinitelyTyped/jasmine/jasmine.d.ts#7de6c3dd94feaeb21f20054b9f30d5dabc5efabd" + "jasmine": "github:DefinitelyTyped/DefinitelyTyped/jasmine/jasmine.d.ts#5c182b9af717f73146399c2485f70f1e2ac0ff2b" } } diff --git a/public/docs/dart/latest/_data.json b/public/docs/dart/latest/_data.json index 20395954fe..5ff6c36d74 100644 --- a/public/docs/dart/latest/_data.json +++ b/public/docs/dart/latest/_data.json @@ -3,7 +3,7 @@ "icon": "home", "title": "Angular Docs", "menuTitle": "Docs Home", - "banner": "Welcome to angular.io/dart! The current Angular 2 release is beta.14. Consult the Change Log about recent enhancements, fixes, and breaking changes." + "banner": "Welcome to angular.io/dart! The current Angular 2 release is beta.15. Consult the Change Log about recent enhancements, fixes, and breaking changes." }, "quickstart": { diff --git a/public/docs/js/latest/_data.json b/public/docs/js/latest/_data.json index 90342c89f3..3e0602f0b7 100644 --- a/public/docs/js/latest/_data.json +++ b/public/docs/js/latest/_data.json @@ -3,7 +3,7 @@ "icon": "home", "title": "Angular Docs", "menuTitle": "Docs Home", - "banner": "Welcome to Angular in JavaScript! The current Angular 2 release is beta.14. Please consult the Change Log about recent enhancements, fixes, and breaking changes." + "banner": "Welcome to Angular in JavaScript! The current Angular 2 release is beta.15. Please consult the Change Log about recent enhancements, fixes, and breaking changes." }, "quickstart": { diff --git a/public/docs/ts/latest/_data.json b/public/docs/ts/latest/_data.json index d0533f5b6e..b0cdb6993b 100644 --- a/public/docs/ts/latest/_data.json +++ b/public/docs/ts/latest/_data.json @@ -3,7 +3,7 @@ "icon": "home", "title": "Angular Docs", "menuTitle": "Docs Home", - "banner": "Welcome to Angular in TypeScript! The current Angular 2 release is beta.14. Please consult the Change Log about recent enhancements, fixes, and breaking changes." + "banner": "Welcome to Angular in TypeScript! The current Angular 2 release is beta.15. Please consult the Change Log about recent enhancements, fixes, and breaking changes." }, "quickstart": { diff --git a/tools/plunker-builder/indexHtmlTranslator.js b/tools/plunker-builder/indexHtmlTranslator.js index 3591c8e47c..c40182adde 100644 --- a/tools/plunker-builder/indexHtmlTranslator.js +++ b/tools/plunker-builder/indexHtmlTranslator.js @@ -35,57 +35,58 @@ var _rxData = [ pattern: 'script', from: 'node_modules/systemjs/dist/system.src.js', //to: ['https://code.angularjs.org/tools/system.js', 'https://code.angularjs.org/tools/typescript.js'] - to: ['https://code.angularjs.org/tools/system.js', 'https://npmcdn.com/typescript@1.8.9/lib/typescript.js'] + //to: ['https://code.angularjs.org/tools/system.js', 'https://npmcdn.com/typescript@1.8.10/lib/typescript.js'] + to: ['https://cdnjs.cloudflare.com/ajax/libs/systemjs/0.19.26/system.js', 'https://npmcdn.com/typescript@1.8.10/lib/typescript.js'] }, { pattern: 'script', from: 'node_modules/angular2/bundles/angular2.dev.js', - to: 'https://code.angularjs.org/2.0.0-beta.14/angular2.dev.js' + to: 'https://code.angularjs.org/2.0.0-beta.15/angular2.dev.js' }, { pattern: 'script', from: 'node_modules/angular2/bundles/angular2-all.umd.dev.js', - to: 'https://code.angularjs.org/2.0.0-beta.14/angular2-all.umd.dev.js' + to: 'https://code.angularjs.org/2.0.0-beta.15/angular2-all.umd.dev.js' }, { pattern: 'script', from: 'node_modules/angular2/bundles/angular2-all.umd.js', - to: 'https://code.angularjs.org/2.0.0-beta.14/angular2-all.umd.dev.js' + to: 'https://code.angularjs.org/2.0.0-beta.15/angular2-all.umd.dev.js' }, { pattern: 'script', from: 'node_modules/angular2/bundles/angular2-polyfills.js', - to: 'https://code.angularjs.org/2.0.0-beta.14/angular2-polyfills.js' + to: 'https://code.angularjs.org/2.0.0-beta.15/angular2-polyfills.js' }, { pattern: 'script', from: 'node_modules/rxjs/bundles/Rx.js', - to: 'https://code.angularjs.org/2.0.0-beta.14/Rx.js' + to: 'https://code.angularjs.org/2.0.0-beta.15/Rx.js' }, { pattern: 'script', from: 'node_modules/rxjs/bundles/Rx.umd.js', - to: 'https://code.angularjs.org/2.0.0-beta.14/Rx.umd.js' + to: 'https://code.angularjs.org/2.0.0-beta.15/Rx.umd.js' }, { pattern: 'script', from: 'node_modules/angular2/bundles/router.dev.js', - to: 'https://code.angularjs.org/2.0.0-beta.14/router.dev.js' + to: 'https://code.angularjs.org/2.0.0-beta.15/router.dev.js' }, { pattern: 'script', from: 'node_modules/angular2/bundles/http.dev.js', - to: 'https://code.angularjs.org/2.0.0-beta.14/http.dev.js' + to: 'https://code.angularjs.org/2.0.0-beta.15/http.dev.js' }, { pattern: 'script', from: 'node_modules/angular2/bundles/testing.dev.js', - to: 'https://code.angularjs.org/2.0.0-beta.14/testing.dev.js' + to: 'https://code.angularjs.org/2.0.0-beta.15/testing.dev.js' }, { pattern: 'script', from: 'node_modules/angular2/es6/dev/src/testing/shims_for_IE.js', - to: 'https://npmcdn.com/angular2@2.0.0-beta.14/es6/dev/src/testing/shims_for_IE.js' + to: 'https://npmcdn.com/angular2@2.0.0-beta.15/es6/dev/src/testing/shims_for_IE.js' }, { pattern: 'script', @@ -95,7 +96,7 @@ var _rxData = [ { pattern: 'script', from: 'node_modules/systemjs/dist/system-polyfills.js', - to: 'https://cdnjs.cloudflare.com/ajax/libs/systemjs/0.19.20/system-polyfills.js' + to: 'https://cdnjs.cloudflare.com/ajax/libs/systemjs/0.19.26/system-polyfills.js' }, { pattern: 'script', From 205cc28f25b9b4aaf9e35a46f889fdc090a6fd3d Mon Sep 17 00:00:00 2001 From: Ken Dale Date: Wed, 13 Apr 2016 18:42:43 -0400 Subject: [PATCH 5/5] docs(lifecycle-hooks): change ngOnit references to ngOnInit closes #1084 --- public/docs/ts/latest/guide/lifecycle-hooks.jade | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/public/docs/ts/latest/guide/lifecycle-hooks.jade b/public/docs/ts/latest/guide/lifecycle-hooks.jade index 1f425fbee9..192e7a9aa2 100644 --- a/public/docs/ts/latest/guide/lifecycle-hooks.jade +++ b/public/docs/ts/latest/guide/lifecycle-hooks.jade @@ -348,7 +348,7 @@ figure.image-display img(src='/resources/images/devguide/lifecycle-hooks/spy-directive.gif' alt="Spy Directive") :marked - Adding a hero results in a new hero `
`. The spy's `ngOnit` logs that event. + Adding a hero results in a new hero `
`. The spy's `ngOnInit` logs that event. We see a new entry for each hero. The *Reset* button clears the `heroes` list. @@ -374,7 +374,7 @@ figure.image-display Constructors should do no more than set the initial local variables to simple values. When a component must start working _soon_ after creation, - we can count on Angular to call the `ngOnit` method to jumpstart it. + we can count on Angular to call the `ngOnInit` method to jumpstart it. That's where the heavy initialization logic belongs. Remember also that a directive's data-bound input properties are not set until _after construction_.