merge from origin/master
This commit is contained in:
commit
5f56e08434
|
@ -10,3 +10,4 @@ tsconfig.json
|
|||
tslint.json
|
||||
npm-debug*.
|
||||
**/protractor.config.js
|
||||
_test-output
|
||||
|
|
|
@ -9,14 +9,14 @@
|
|||
<!-- 1. Load libraries -->
|
||||
<!-- IE required polyfills (from CDN), in this exact order -->
|
||||
<script src="https://cdnjs.cloudflare.com/ajax/libs/es6-shim/0.35.0/es6-shim.min.js"></script>
|
||||
<script src="https://cdnjs.cloudflare.com/ajax/libs/systemjs/0.19.25/system-polyfills.js"></script>
|
||||
<script src="https://cdnjs.cloudflare.com/ajax/libs/systemjs/0.19.26/system-polyfills.js"></script>
|
||||
<script src="https://npmcdn.com/angular2/es6/dev/src/testing/shims_for_IE.js"></script>
|
||||
|
||||
<script src="https://code.angularjs.org/tools/system.js"></script>
|
||||
<script src="https://code.angularjs.org/tools/typescript.js"></script>
|
||||
<script src="https://code.angularjs.org/2.0.0-beta.14/angular2-polyfills.js"></script>
|
||||
<script src="https://code.angularjs.org/2.0.0-beta.14/Rx.js"></script>
|
||||
<script src="https://code.angularjs.org/2.0.0-beta.14/angular2.dev.js"></script>
|
||||
<script src="https://code.angularjs.org/2.0.0-beta.15/angular2-polyfills.js"></script>
|
||||
<script src="https://code.angularjs.org/2.0.0-beta.15/Rx.js"></script>
|
||||
<script src="https://code.angularjs.org/2.0.0-beta.15/angular2.dev.js"></script>
|
||||
|
||||
<!-- 2. Configure SystemJS -->
|
||||
<script>
|
||||
|
|
|
@ -10,14 +10,14 @@
|
|||
<!-- 1. Load libraries -->
|
||||
<!-- IE required polyfills (from CDN), in this exact order -->
|
||||
<script src="https://cdnjs.cloudflare.com/ajax/libs/es6-shim/0.35.0/es6-shim.min.js"></script>
|
||||
<script src="https://cdnjs.cloudflare.com/ajax/libs/systemjs/0.19.25/system-polyfills.js"></script>
|
||||
<script src="https://cdnjs.cloudflare.com/ajax/libs/systemjs/0.19.26/system-polyfills.js"></script>
|
||||
<script src="https://npmcdn.com/angular2/es6/dev/src/testing/shims_for_IE.js"></script>
|
||||
|
||||
<script src="https://code.angularjs.org/tools/system.js"></script>
|
||||
<script src="https://code.angularjs.org/tools/typescript.js"></script>
|
||||
<script src="https://code.angularjs.org/2.0.0-beta.14/angular2-polyfills.js"></script>
|
||||
<script src="https://code.angularjs.org/2.0.0-beta.14/Rx.js"></script>
|
||||
<script src="https://code.angularjs.org/2.0.0-beta.14/angular2.dev.js"></script>
|
||||
<script src="https://code.angularjs.org/2.0.0-beta.15/angular2-polyfills.js"></script>
|
||||
<script src="https://code.angularjs.org/2.0.0-beta.15/Rx.js"></script>
|
||||
<script src="https://code.angularjs.org/2.0.0-beta.15/angular2.dev.js"></script>
|
||||
|
||||
<!-- 2. Configure SystemJS -->
|
||||
<script>
|
||||
|
|
|
@ -10,14 +10,14 @@
|
|||
<!-- 1. Load libraries -->
|
||||
<!-- IE required polyfills (from CDN), in this exact order -->
|
||||
<script src="https://cdnjs.cloudflare.com/ajax/libs/es6-shim/0.35.0/es6-shim.min.js"></script>
|
||||
<script src="https://cdnjs.cloudflare.com/ajax/libs/systemjs/0.19.25/system-polyfills.js"></script>
|
||||
<script src="https://cdnjs.cloudflare.com/ajax/libs/systemjs/0.19.26/system-polyfills.js"></script>
|
||||
<script src="https://npmcdn.com/angular2/es6/dev/src/testing/shims_for_IE.js"></script>
|
||||
|
||||
<script src="https://code.angularjs.org/tools/system.js"></script>
|
||||
<script src="https://code.angularjs.org/tools/typescript.js"></script>
|
||||
<script src="https://code.angularjs.org/2.0.0-beta.14/angular2-polyfills.js"></script>
|
||||
<script src="https://code.angularjs.org/2.0.0-beta.14/Rx.js"></script>
|
||||
<script src="https://code.angularjs.org/2.0.0-beta.14/angular2.dev.js"></script>
|
||||
<script src="https://code.angularjs.org/2.0.0-beta.15/angular2-polyfills.js"></script>
|
||||
<script src="https://code.angularjs.org/2.0.0-beta.15/Rx.js"></script>
|
||||
<script src="https://code.angularjs.org/2.0.0-beta.15/angular2.dev.js"></script>
|
||||
|
||||
<!-- 2. Configure SystemJS -->
|
||||
<script>
|
||||
|
|
|
@ -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);
|
||||
}
|
||||
|
||||
})();
|
||||
|
|
|
@ -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
|
||||
})
|
||||
}
|
||||
|
|
|
@ -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
|
||||
})
|
||||
}
|
|
@ -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
|
||||
})
|
||||
}
|
|
@ -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",
|
||||
|
@ -20,21 +20,21 @@
|
|||
"author": "",
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"angular2": "2.0.0-beta.14",
|
||||
"systemjs": "0.19.25",
|
||||
"angular2": "2.0.0-beta.15",
|
||||
"systemjs": "0.19.26",
|
||||
"es6-shim": "^0.35.0",
|
||||
"reflect-metadata": "0.1.2",
|
||||
"rxjs": "5.0.0-beta.2",
|
||||
"zone.js": "0.6.6",
|
||||
"zone.js": "0.6.10",
|
||||
|
||||
"a2-in-memory-web-api": "^0.1.14",
|
||||
"a2-in-memory-web-api": "^0.1.15",
|
||||
"bootstrap": "^3.3.6"
|
||||
|
||||
},
|
||||
"devDependencies": {
|
||||
"concurrently": "^2.0.0",
|
||||
"lite-server": "^2.2.0",
|
||||
"typescript": "^1.8.9",
|
||||
"typescript": "^1.8.10",
|
||||
"typings":"^0.7.12",
|
||||
|
||||
"http-server": "^0.9.0",
|
||||
|
@ -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",
|
||||
|
|
|
@ -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;
|
||||
}
|
||||
}
|
|
@ -7,11 +7,11 @@
|
|||
},
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"angular2": "2.0.0-beta.14",
|
||||
"angular2": "2.0.0-beta.15",
|
||||
"es6-shim": "^0.35.0",
|
||||
"reflect-metadata": "0.1.2",
|
||||
"rxjs": "5.0.0-beta.2",
|
||||
"zone.js": "0.6.6"
|
||||
"zone.js": "0.6.10"
|
||||
},
|
||||
"devDependencies": {
|
||||
"concurrently": "^2.0.0",
|
||||
|
|
|
@ -11,17 +11,17 @@
|
|||
},
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"angular2": "2.0.0-beta.14",
|
||||
"systemjs": "0.19.25",
|
||||
"angular2": "2.0.0-beta.15",
|
||||
"systemjs": "0.19.26",
|
||||
"es6-shim": "^0.35.0",
|
||||
"reflect-metadata": "0.1.2",
|
||||
"rxjs": "5.0.0-beta.2",
|
||||
"zone.js": "0.6.6"
|
||||
"zone.js": "0.6.10"
|
||||
},
|
||||
"devDependencies": {
|
||||
"concurrently": "^2.0.0",
|
||||
"lite-server": "^2.2.0",
|
||||
"typescript": "^1.8.9",
|
||||
"typescript": "^1.8.10",
|
||||
"typings":"^0.7.12"
|
||||
}
|
||||
}
|
||||
|
|
|
@ -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"
|
||||
}
|
||||
}
|
||||
|
|
|
@ -6,7 +6,7 @@
|
|||
<!-- #docregion base-href -->
|
||||
<base href="/">
|
||||
<!-- #enddocregion base-href -->
|
||||
|
||||
|
||||
<title>Router Sample</title>
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<link rel="stylesheet" href="styles.css">
|
||||
|
@ -15,22 +15,22 @@
|
|||
<!-- IE required polyfills, in this exact order -->
|
||||
<script src="node_modules/es6-shim/es6-shim.min.js"></script>
|
||||
<script src="node_modules/systemjs/dist/system-polyfills.js"></script>
|
||||
<script src="node_modules/angular2/es6/dev/src/testing/shims_for_IE.js"></script>
|
||||
<script src="node_modules/angular2/es6/dev/src/testing/shims_for_IE.js"></script>
|
||||
<!-- #enddocregion ie-polyfills -->
|
||||
|
||||
<script src="node_modules/angular2/bundles/angular2-polyfills.js"></script>
|
||||
<script src="node_modules/systemjs/dist/system.src.js"></script>
|
||||
<script src="node_modules/rxjs/bundles/Rx.js"></script>
|
||||
<script src="node_modules/angular2/bundles/angular2.dev.js"></script>
|
||||
|
||||
|
||||
<!-- Add the router library -->
|
||||
<!-- #docregion router-lib -->
|
||||
<script src="node_modules/angular2/bundles/router.dev.js"></script>
|
||||
<!-- #enddocregion router-lib -->
|
||||
|
||||
|
||||
<script>
|
||||
System.config({
|
||||
packages: {
|
||||
packages: {
|
||||
app: {
|
||||
format: 'register',
|
||||
defaultExtension: 'js'
|
||||
|
|
|
@ -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);
|
||||
// #docregion http-providers
|
||||
bootstrap(TohComponent, [HTTP_PROVIDERS]);
|
||||
// #enddocregion http-providers
|
||||
|
|
|
@ -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: `
|
||||
<h3>Heroes:</h3>
|
||||
<ul>
|
||||
<li *ngFor="#hero of heroes">
|
||||
{{ hero.name }}
|
||||
</li>
|
||||
</ul>
|
||||
New Hero:
|
||||
<input #newHero />
|
||||
<button (click)="addHero(newHero.value); newHero.value=''">
|
||||
Add Hero
|
||||
</button>
|
||||
<div class="error" *ngIf="errorMessage">{{errorMessage}}</div>
|
||||
`,
|
||||
// #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(); }
|
||||
|
||||
|
|
|
@ -0,0 +1,13 @@
|
|||
<!-- #docregion -->
|
||||
<h3>Heroes:</h3>
|
||||
<ul>
|
||||
<li *ngFor="#hero of heroes">
|
||||
{{ hero.name }}
|
||||
</li>
|
||||
</ul>
|
||||
New Hero:
|
||||
<input #newHero />
|
||||
<button (click)="addHero(newHero.value); newHero.value=''">
|
||||
Add Hero
|
||||
</button>
|
||||
<div class="error" *ngIf="errorMessage">{{errorMessage}}</div>
|
|
@ -5,20 +5,7 @@ import {HeroService} from './hero.service';
|
|||
|
||||
@Component({
|
||||
selector: 'hero-list',
|
||||
template: `
|
||||
<h3>Heroes:</h3>
|
||||
<ul>
|
||||
<li *ngFor="#hero of heroes">
|
||||
{{ hero.name }}
|
||||
</li>
|
||||
</ul>
|
||||
New Hero:
|
||||
<input #newHero />
|
||||
<button (click)="addHero(newHero.value); newHero.value=''">
|
||||
Add Hero
|
||||
</button>
|
||||
<div class="error" *ngIf="errorMessage">{{errorMessage}}</div>
|
||||
`,
|
||||
templateUrl: 'app/toh/hero-list.component.html',
|
||||
styles: ['.error {color:red;}']
|
||||
})
|
||||
// #docregion component
|
||||
|
|
|
@ -1,4 +1,4 @@
|
|||
/* Promise version */
|
||||
// ToH Promise Version
|
||||
// #docplaster
|
||||
|
||||
// #docregion
|
||||
|
@ -15,30 +15,39 @@ export class HeroService {
|
|||
private _heroesUrl = 'app/heroes.json';
|
||||
|
||||
// #docregion methods
|
||||
getHeroes () {
|
||||
getHeroes (): Promise<Hero[]> {
|
||||
return this.http.get(this._heroesUrl)
|
||||
.toPromise()
|
||||
.then(res => <Hero[]> 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<Hero> {
|
||||
addHero (name: string): Promise<Hero> {
|
||||
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 => <Hero> res.json().data)
|
||||
.then(this.extractData)
|
||||
.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');
|
||||
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 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);
|
||||
}
|
||||
|
||||
// #enddocregion methods
|
||||
}
|
||||
// #enddocregion
|
||||
|
|
|
@ -31,42 +31,48 @@ export class HeroService {
|
|||
// #enddocregion endpoint
|
||||
|
||||
// #docregion methods
|
||||
// #docregion error-handling
|
||||
getHeroes () {
|
||||
// #docregion http-get, http-get-v1
|
||||
// #docregion error-handling, http-get
|
||||
getHeroes (): Observable<Hero[]> {
|
||||
return this.http.get(this._heroesUrl)
|
||||
.map(res => <Hero[]> res.json().data)
|
||||
// #enddocregion v1, http-get-v1, error-handling
|
||||
.do(data => console.log(data)) // eyeball results in the console
|
||||
// #docregion v1, http-get-v1, error-handling
|
||||
.map(this.extractData)
|
||||
.catch(this.handleError);
|
||||
// #enddocregion http-get, http-get-v1
|
||||
}
|
||||
// #enddocregion error-handling
|
||||
// #enddocregion error-handling, http-get
|
||||
// #enddocregion v1
|
||||
|
||||
// #docregion addhero
|
||||
addHero (name: string) : Observable<Hero> {
|
||||
addHero (name: string): Observable<Hero> {
|
||||
|
||||
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 => <Hero> res.json().data)
|
||||
.catch(this.handleError)
|
||||
// #enddocregion headers
|
||||
.map(this.extractData)
|
||||
.catch(this.handleError);
|
||||
}
|
||||
// #enddocregion addhero
|
||||
|
||||
// #docregion v1
|
||||
|
||||
// #docregion extract-data
|
||||
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 || { };
|
||||
}
|
||||
// #enddocregion extract-data
|
||||
|
||||
// #docregion error-handling
|
||||
private handleError (error: Response) {
|
||||
// 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');
|
||||
private handleError (error: any) {
|
||||
// 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
|
||||
// #enddocregion methods
|
||||
|
|
|
@ -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: `
|
||||
<h1>Tour of Heroes</h1>
|
||||
<hero-list></hero-list>
|
||||
`,
|
||||
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 { }
|
|
@ -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: `
|
||||
<h1>Tour of Heroes</h1>
|
||||
<hero-list></hero-list>
|
||||
`,
|
||||
// #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
|
|
@ -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';
|
|||
<hero-list></hero-list>
|
||||
`,
|
||||
// #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 { }
|
||||
|
|
|
@ -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: `
|
||||
<pre>{{heroes | json}}</pre>
|
||||
`,
|
||||
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);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,9 @@
|
|||
// #docplaster
|
||||
|
||||
// #docregion
|
||||
/* recommended */
|
||||
|
||||
export class Hero {
|
||||
id: number;
|
||||
name: string;
|
||||
}
|
|
@ -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);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,9 @@
|
|||
// #docplaster
|
||||
|
||||
// #docregion
|
||||
/* recommended */
|
||||
|
||||
import { bootstrap } from 'angular2/platform/browser';
|
||||
import { AppComponent } from './app.component';
|
||||
|
||||
bootstrap(AppComponent, []);
|
|
@ -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: `
|
||||
<h1>{{title}}</h1>
|
||||
<pre>{{heroes | json}}</pre>
|
||||
`,
|
||||
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: `
|
||||
<pre>{{heroes | json}}</pre>
|
||||
`,
|
||||
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
|
|
@ -0,0 +1,50 @@
|
|||
<!DOCTYPE html>
|
||||
<!-- #docregion -->
|
||||
<html>
|
||||
<head>
|
||||
<!-- Set the base href -->
|
||||
<!-- #docregion base-href -->
|
||||
<base href="/">
|
||||
<!-- #enddocregion base-href -->
|
||||
|
||||
<title>Style Guide Sample</title>
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<link rel="stylesheet" href="styles.css">
|
||||
|
||||
<!-- #docregion ie-polyfills -->
|
||||
<!-- IE required polyfills, in this exact order -->
|
||||
<script src="node_modules/es6-shim/es6-shim.min.js"></script>
|
||||
<script src="node_modules/systemjs/dist/system-polyfills.js"></script>
|
||||
<script src="node_modules/angular2/es6/dev/src/testing/shims_for_IE.js"></script>
|
||||
<!-- #enddocregion ie-polyfills -->
|
||||
|
||||
<script src="node_modules/angular2/bundles/angular2-polyfills.js"></script>
|
||||
<script src="node_modules/systemjs/dist/system.src.js"></script>
|
||||
<script src="node_modules/rxjs/bundles/Rx.js"></script>
|
||||
<script src="node_modules/angular2/bundles/angular2.dev.js"></script>
|
||||
|
||||
<!-- Add the router library -->
|
||||
<!-- #docregion router-lib -->
|
||||
<script src="node_modules/angular2/bundles/router.dev.js"></script>
|
||||
<!-- #enddocregion router-lib -->
|
||||
|
||||
<script>
|
||||
System.config({
|
||||
packages: {
|
||||
app: {
|
||||
format: 'register',
|
||||
defaultExtension: 'js'
|
||||
}
|
||||
}
|
||||
});
|
||||
System.import('app/main')
|
||||
.then(null, console.error.bind(console));
|
||||
</script>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<my-app>loading...</my-app>
|
||||
</body>
|
||||
|
||||
</html>
|
||||
<!-- #enddocregion -->
|
|
@ -0,0 +1,8 @@
|
|||
{
|
||||
"description": "Style Guide",
|
||||
"files":[
|
||||
"!**/*.d.ts",
|
||||
"!**/*.js"
|
||||
],
|
||||
"tags": ["style guide, styleguide"]
|
||||
}
|
|
@ -1,5 +1,5 @@
|
|||
// #docregion
|
||||
export interface Hero {
|
||||
export class Hero {
|
||||
id: number;
|
||||
name: string;
|
||||
}
|
||||
|
|
|
@ -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();
|
||||
}));
|
||||
});
|
||||
});
|
|
@ -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<Hero[]> {
|
||||
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<Hero> {
|
||||
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 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);
|
||||
}
|
||||
}
|
|
@ -0,0 +1 @@
|
|||
<span>from external template</span>
|
|
@ -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 = <ButtonComp> 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, '<span>Mock</span>')
|
||||
.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: '<span>Modified {{childBinding}}</span>'})
|
||||
)
|
||||
.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(); };
|
||||
(<any>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(); };
|
||||
(<any>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();
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
|
@ -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: `<button (click)='clicked()'>Click me!</button>`
|
||||
})
|
||||
export class ButtonComp {
|
||||
wasClicked = false;
|
||||
clicked() { this.wasClicked = true; }
|
||||
}
|
||||
|
||||
|
||||
@Component({
|
||||
selector: 'child-comp',
|
||||
template: `<span>Original {{childBinding}}</span>`
|
||||
})
|
||||
export class ChildComp {
|
||||
childBinding = 'Child';
|
||||
}
|
||||
|
||||
|
||||
@Component({
|
||||
selector: 'child-comp',
|
||||
template: `<span>Mock</span>`
|
||||
})
|
||||
export class MockChildComp { }
|
||||
|
||||
|
||||
@Component({
|
||||
selector: 'parent-comp',
|
||||
template: `Parent(<child-comp></child-comp>)`,
|
||||
directives: [ChildComp]
|
||||
})
|
||||
export class ParentComp { }
|
||||
|
||||
|
||||
@Component({
|
||||
selector: 'my-if-comp',
|
||||
template: `MyIf(<span *ngIf="showMore">More</span>)`,
|
||||
directives: [NgIf]
|
||||
})
|
||||
export class MyIfComp {
|
||||
showMore: boolean = false;
|
||||
}
|
||||
|
||||
|
||||
@Component({
|
||||
selector: 'child-child-comp',
|
||||
template: '<span>ChildChild</span>'
|
||||
})
|
||||
export class ChildChildComp { }
|
||||
|
||||
|
||||
@Component({
|
||||
selector: 'child-comp',
|
||||
template: `<span>Original {{childBinding}}(<child-child-comp></child-child-comp>)</span>`,
|
||||
directives: [ChildChildComp]
|
||||
})
|
||||
export class ChildWithChildComp {
|
||||
childBinding = 'Child';
|
||||
}
|
||||
|
||||
|
||||
@Component({
|
||||
selector: 'child-child-comp',
|
||||
template: `<span>ChildChild Mock</span>`
|
||||
})
|
||||
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 { }
|
|
@ -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();
|
||||
}
|
||||
|
||||
|
||||
})();
|
|
@ -0,0 +1,32 @@
|
|||
<!-- #docregion -->
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta http-equiv="content-type" content="text/html;charset=utf-8">
|
||||
<title>Angular Public Unit Tests</title>
|
||||
<link rel="stylesheet" href="node_modules/jasmine-core/lib/jasmine-core/jasmine.css">
|
||||
|
||||
<script src="node_modules/jasmine-core/lib/jasmine-core/jasmine.js"></script>
|
||||
<script src="node_modules/jasmine-core/lib/jasmine-core/jasmine-html.js"></script>
|
||||
<script src="node_modules/jasmine-core/lib/jasmine-core/boot.js"></script>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<script src="node_modules/es6-shim/es6-shim.min.js"></script>
|
||||
<script src="node_modules/systemjs/dist/system-polyfills.js"></script>
|
||||
<script src="node_modules/angular2/es6/dev/src/testing/shims_for_IE.js"></script>
|
||||
|
||||
<script src="node_modules/angular2/bundles/angular2-polyfills.js"></script>
|
||||
<script src="node_modules/systemjs/dist/system.src.js"></script>
|
||||
<script src="node_modules/rxjs/bundles/Rx.js"></script>
|
||||
<script src="node_modules/angular2/bundles/angular2.dev.js"></script>
|
||||
|
||||
<script src="node_modules/angular2/bundles/testing.dev.js"></script>
|
||||
|
||||
<script>
|
||||
var __spec_files__ = ['app/public.spec'];
|
||||
</script>
|
||||
<script src="test-shim.js"></script>
|
||||
</body>
|
||||
|
||||
</html>
|
|
@ -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"
|
||||
}
|
||||
}
|
||||
|
|
|
@ -3,7 +3,7 @@
|
|||
"icon": "home",
|
||||
"title": "Angular Docs",
|
||||
"menuTitle": "Docs Home",
|
||||
"banner": "Welcome to <b>angular.io/dart</b>! The current Angular 2 release is <b>beta.14</b>. Consult the <a href='https://github.com/angular/angular/blob/master/CHANGELOG.md' target='_blank'>Change Log</a> about recent enhancements, fixes, and breaking changes."
|
||||
"banner": "Welcome to <b>angular.io/dart</b>! The current Angular 2 release is <b>beta.15</b>. Consult the <a href='https://github.com/angular/angular/blob/master/CHANGELOG.md' target='_blank'>Change Log</a> about recent enhancements, fixes, and breaking changes."
|
||||
},
|
||||
|
||||
"quickstart": {
|
||||
|
|
|
@ -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",
|
||||
|
|
|
@ -0,0 +1 @@
|
|||
!= partial("../../../_includes/_ts-temp")
|
|
@ -3,7 +3,7 @@
|
|||
"icon": "home",
|
||||
"title": "Angular Docs",
|
||||
"menuTitle": "Docs Home",
|
||||
"banner": "Welcome to <b>Angular in JavaScript</b>! The current Angular 2 release is <b>beta.14</b>. Please consult the <a href='https://github.com/angular/angular/blob/master/CHANGELOG.md' target='_blank'> Change Log</a> about recent enhancements, fixes, and breaking changes."
|
||||
"banner": "Welcome to <b>Angular in JavaScript</b>! The current Angular 2 release is <b>beta.15</b>. Please consult the <a href='https://github.com/angular/angular/blob/master/CHANGELOG.md' target='_blank'> Change Log</a> about recent enhancements, fixes, and breaking changes."
|
||||
},
|
||||
|
||||
"quickstart": {
|
||||
|
|
|
@ -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",
|
||||
|
|
|
@ -0,0 +1 @@
|
|||
!= partial("../../../_includes/_ts-temp")
|
|
@ -3,7 +3,7 @@
|
|||
"icon": "home",
|
||||
"title": "Angular文档",
|
||||
"menuTitle": "文档首页",
|
||||
"banner": "欢迎来到 <b>Angular in TypeScript</b>! 当前的Angular版本是 <b>beta.14</b>。请参考<a href='https://github.com/angular/angular/blob/master/CHANGELOG.md' target='_blank'>Change Log</a>来了解最近的增强、修正和破坏性变更。"
|
||||
"banner": "欢迎来到 <b>Angular in TypeScript</b>! 当前的Angular版本是 <b>beta.15</b>。请参考<a href='https://github.com/angular/angular/blob/master/CHANGELOG.md' target='_blank'>Change Log</a>来了解最近的增强、修正和破坏性变更。"
|
||||
},
|
||||
|
||||
"quickstart": {
|
||||
|
|
|
@ -103,6 +103,12 @@
|
|||
"intro": "Angular有一个强力的模板引擎,它能让你轻松维护元素的DOM树结构。"
|
||||
},
|
||||
|
||||
"style-guide": {
|
||||
"title": "风格指南",
|
||||
"intro": "按正确的风格编写Angular 2应用。",
|
||||
"hide": true
|
||||
},
|
||||
|
||||
"testing": {
|
||||
"title": "测试",
|
||||
"intro": "Angular 2应用的测试技术与实践。"
|
||||
|
|
|
@ -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 `<div>`. The spy's `ngOnit` logs that event.
|
||||
Adding a hero results in a new hero `<div>`. 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_.
|
||||
|
|
|
@ -21,7 +21,6 @@ include ../_util-fns
|
|||
[Enabling RxJS Operators](#enable-rxjs-operators)<br>
|
||||
[Extract JSON data with RxJS map](#map)<br>
|
||||
[Error handling](#error-handling)<br>
|
||||
[Log results to console](#do)<br>
|
||||
[Send data to the server](#update)<br>
|
||||
[Add headers](#headers)<br>
|
||||
[Promises instead of observables](#promises)<br>
|
||||
|
@ -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<Response>`) 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
|
||||
<a id="map"></a>
|
||||
### 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"></a>
|
||||
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!
|
||||
<a id="do"></a>
|
||||
<a id="console-log"></a>
|
||||
: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!
|
||||
|
||||
|
||||
<a id="update"></a>
|
||||
<a id="post"></a>
|
||||
|
@ -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.
|
||||
|
|
|
@ -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
|
||||
<a id="001"></a>
|
||||
#### 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.
|
||||
|
||||
<a href="#toc">Back to top</a>
|
||||
|
||||
:marked
|
||||
### Small Functions
|
||||
<a id="002"></a>
|
||||
#### 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.
|
||||
|
||||
<a href="#toc">Back to top</a>
|
||||
:marked
|
||||
## Components
|
||||
|
||||
### Member Sequence
|
||||
<a id="033"></a>
|
||||
#### 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);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
<a href="#toc">Back to top</a>
|
||||
:marked
|
||||
### Defer Logic to Services
|
||||
<a id="035"></a>
|
||||
#### 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) => <Session[]>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();
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
<a href="#toc">Back to top</a>
|
||||
|
||||
:marked
|
||||
## Services
|
||||
|
||||
### Singletons
|
||||
<a id="040"></a>
|
||||
#### 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) => <Session[]>response.json().data)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
<a href="#toc">Back to top</a>
|
||||
|
||||
:marked
|
||||
### Providing a Service
|
||||
<a id="041"></a>
|
||||
#### 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: `
|
||||
<my-speakers></my-speakers>
|
||||
`,
|
||||
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: `
|
||||
<pre>{{speakers | json}}</pre>
|
||||
`
|
||||
})
|
||||
export class SpeakerListComponent implements OnInit{
|
||||
speakers: Speaker[] = [];
|
||||
|
||||
constructor(private _speakerService: SpeakerService) {}
|
||||
|
||||
ngOnInit() {
|
||||
this._speakerService.getSpeakers().then(speakers => this.speakers = speakers);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
<a href="#toc">Back to top</a>
|
||||
:marked
|
||||
### Single Responsibility
|
||||
<a id="042"></a>
|
||||
#### 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.
|
||||
|
||||
<a href="#toc">Back to top</a>
|
||||
:marked
|
||||
## Data Services
|
||||
|
||||
### Separate Data Calls
|
||||
<a id="050"></a>
|
||||
#### 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();
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
<a href="#toc">Back to top</a>
|
||||
:marked
|
||||
## Naming
|
||||
|
||||
### Naming Guidelines
|
||||
<a id="100"></a>
|
||||
#### 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.
|
||||
|
||||
<a href="#toc">Back to top</a>
|
||||
:marked
|
||||
### File Names
|
||||
<a id="101"></a>
|
||||
#### 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
|
||||
```
|
||||
|
||||
<a href="#toc">Back to top</a>
|
||||
:marked
|
||||
### Test File Names
|
||||
<a id="102"></a>
|
||||
#### 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
|
||||
```
|
||||
|
||||
<a href="#toc">Back to top</a>
|
||||
:marked
|
||||
### Component Names
|
||||
<a id="103"></a>
|
||||
#### 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
|
||||
```
|
||||
|
||||
<a href="#toc">Back to top</a>
|
||||
:marked
|
||||
### Suffixes
|
||||
<a id="104"></a>
|
||||
#### 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 { }
|
||||
```
|
||||
|
||||
<a href="#toc">Back to top</a>
|
||||
:marked
|
||||
### Service Names
|
||||
<a id="110"></a>
|
||||
#### 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
|
||||
```
|
||||
|
||||
<a href="#toc">Back to top</a>
|
||||
: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.
|
||||
|
||||
<a href="#toc">Back to top</a>
|
||||
:marked
|
||||
### Component Router
|
||||
<a id="130"></a>
|
||||
#### Style 130
|
||||
|
||||
- Separate route configuration into a routing component file, also known as a component router.
|
||||
|
||||
- Use a `<router-outlet>` 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 `<router-outlet>` 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 { }
|
||||
```
|
||||
|
||||
<a href="#toc">Back to top</a>
|
||||
:marked
|
||||
### Route Naming
|
||||
<a id="131"></a>
|
||||
#### 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 }
|
||||
```
|
||||
|
||||
<a href="#toc">Back to top</a>
|
||||
:marked
|
||||
## Application Structure LIFT Principle
|
||||
### LIFT
|
||||
<a id="140"></a>
|
||||
#### 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?
|
||||
|
||||
<a href="#toc">Back to top</a>
|
||||
:marked
|
||||
### Locate
|
||||
<a id="141"></a>
|
||||
#### 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
|
||||
```
|
||||
|
||||
<a href="#toc">Back to top</a>
|
||||
:marked
|
||||
### Identify
|
||||
<a id="142"></a>
|
||||
#### 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.
|
||||
|
||||
<a href="#toc">Back to top</a>
|
||||
:marked
|
||||
### Flat
|
||||
<a id="143"></a>
|
||||
#### 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.
|
||||
|
||||
<a href="#toc">Back to top</a>
|
||||
:marked
|
||||
### T-DRY (Try to Stick to DRY)
|
||||
<a id="144"></a>
|
||||
#### 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.
|
||||
|
||||
<a href="#toc">Back to top</a>
|
||||
:marked
|
||||
## Application Structure
|
||||
|
||||
### Overall Guidelines
|
||||
<a id="150"></a>
|
||||
#### 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**
|
||||
|
||||
<a href="#toc">Back to top</a>
|
||||
:marked
|
||||
### Layout
|
||||
<a id="151"></a>
|
||||
#### 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.
|
||||
|
||||
<a href="#toc">Back to top</a>
|
||||
:marked
|
||||
### Folders-by-Feature Structure
|
||||
<a id="152"></a>
|
||||
#### 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**
|
||||
|
||||
<a href="#toc">Back to top</a>
|
||||
: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)
|
||||
|
||||
<a href="#toc">Back to top</a>
|
Binary file not shown.
Before Width: | Height: | Size: 24 KiB After Width: | Height: | Size: 12 KiB |
|
@ -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',
|
||||
|
|
Loading…
Reference in New Issue