天天看點

angularjs2 依賴注入

<!DOCTYPE html>
<html>
<head>
    <title>Dependency Injection</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="styles.css" target="_blank" rel="external nofollow" >

    <!-- Polyfill(s) for older browsers -->
    <script src="https://unpkg.com/core-js/client/shim.min.js"></script>

    <script src="https://unpkg.com/[email protected]?main=browser"></script>
    <script src="https://unpkg.com/[email protected]"></script>
    <script src="https://unpkg.com/[email protected]/dist/system.src.js"></script>

    <script src="systemjs.config.js"></script>
    <script>
        System.import('app').catch(function(err){ console.error(err); });
    </script>
</head>

<body>
<my-app>Loading my-app ...</my-app>
</body>

</html>


<!-- 
Copyright 2016 Google Inc. All Rights Reserved.
Use of this source code is governed by an MIT-style license that
can be found in the LICENSE file at http://angular.io/license
-->
           
/**
 * PLUNKER VERSION
 * (based on systemjs.config.js in angular.io)
 * System configuration for Angular 2 samples
 * Adjust as necessary for your application needs.
 */
(function (global) {
    System.config({
        // DEMO ONLY! REAL CODE SHOULD NOT TRANSPILE IN THE BROWSER
        transpiler: 'ts',
        typescriptOptions: {
            tsconfig: true
        },
        meta: {
            'typescript': {
                "exports": "ts"
            }
        },
        paths: {
            // paths serve as alias
            'npm:': 'https://unpkg.com/'
        },
        // map tells the System loader where to look for things
        map: {
            // our app is within the app folder
            app: 'app',

            // angular bundles
            '@angular/core': 'npm:@angular/core/bundles/core.umd.js',
            '@angular/common': 'npm:@angular/common/bundles/common.umd.js',
            '@angular/compiler': 'npm:@angular/compiler/bundles/compiler.umd.js',
            '@angular/platform-browser': 'npm:@angular/platform-browser/bundles/platform-browser.umd.js',
            '@angular/platform-browser-dynamic': 'npm:@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js',
            '@angular/http': 'npm:@angular/http/bundles/http.umd.js',
            '@angular/router': 'npm:@angular/router/bundles/router.umd.js',
            '@angular/forms': 'npm:@angular/forms/bundles/forms.umd.js',

            // other libraries
            'rxjs':                       'npm:rxjs',
            'angular2-in-memory-web-api': 'npm:angular2-in-memory-web-api',
            'ts':                         'npm:[email protected]/lib/plugin.js',
            'typescript':                 'npm:[email protected]/lib/typescript.js',

        },
        // packages tells the System loader how to load when no filename and/or no extension
        packages: {
            app: {
                main: './main.ts',
                defaultExtension: 'ts'
            },
            rxjs: {
                defaultExtension: 'js'
            },
            'angular2-in-memory-web-api': {
                main: './index.js',
                defaultExtension: 'js'
            }
        }
    });
})(this);
           
{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "moduleResolution": "node",
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "removeComments": false,
    "noImplicitAny": true,
    "suppressImplicitAnyIndexErrors": true
  }
}
           
/* Master Styles */
h1 {
    color: #369;
    font-family: Arial, Helvetica, sans-serif;
    font-size: 250%;
}
h2, h3 {
    color: #444;
    font-family: Arial, Helvetica, sans-serif;
    font-weight: lighter;
}
body {
    margin: 2em;
}
body, input[text], button {
    color: #888;
    font-family: Cambria, Georgia;
}
a {
    cursor: pointer;
    cursor: hand;
}
button {
    font-family: Arial;
    background-color: #eee;
    border: none;
    padding: 5px 10px;
    border-radius: 4px;
    cursor: pointer;
    cursor: hand;
}
button:hover {
    background-color: #cfd8dc;
}
button:disabled {
    background-color: #eee;
    color: #aaa;
    cursor: auto;
}

/* Navigation link styles */
nav a {
    padding: 5px 10px;
    text-decoration: none;
    margin-top: 10px;
    display: inline-block;
    background-color: #eee;
    border-radius: 4px;
}
nav a:visited, a:link {
    color: #607D8B;
}
nav a:hover {
    color: #039be5;
    background-color: #CFD8DC;
}
nav a.active {
    color: #039be5;
}

/* items class */
.items {
    margin: 0 0 2em 0;
    list-style-type: none;
    padding: 0;
    width: 24em;
}
.items li {
    cursor: pointer;
    position: relative;
    left: 0;
    background-color: #EEE;
    margin: .5em;
    padding: .3em 0;
    height: 1.6em;
    border-radius: 4px;
}
.items li:hover {
    color: #607D8B;
    background-color: #DDD;
    left: .1em;
}
.items li.selected:hover {
    background-color: #BBD8DC;
    color: white;
}
.items .text {
    position: relative;
    top: -3px;
}
.items {
    margin: 0 0 2em 0;
    list-style-type: none;
    padding: 0;
    width: 24em;
}
.items li {
    cursor: pointer;
    position: relative;
    left: 0;
    background-color: #EEE;
    margin: .5em;
    padding: .3em 0;
    height: 1.6em;
    border-radius: 4px;
}
.items li:hover {
    color: #607D8B;
    background-color: #DDD;
    left: .1em;
}
.items li.selected {
    background-color: #CFD8DC;
    color: white;
}

.items li.selected:hover {
    background-color: #BBD8DC;
}
.items .text {
    position: relative;
    top: -3px;
}
.items .badge {
    display: inline-block;
    font-size: small;
    color: white;
    padding: 0.8em 0.7em 0 0.7em;
    background-color: #607D8B;
    line-height: 1em;
    position: relative;
    left: -1px;
    top: -4px;
    height: 1.8em;
    margin-right: .8em;
    border-radius: 4px 0 0 4px;
}
/* everywhere else */
* {
    font-family: Arial, Helvetica, sans-serif;
}


/*
Copyright 2016 Google Inc. All Rights Reserved.
Use of this source code is governed by an MIT-style license that
can be found in the LICENSE file at http://angular.io/license
*/
           
import { Component } from '@angular/core';
import {Hero} from "./hero";
import {UserService} from "./user-service";
import {Logger} from "./logger-service";
import {EvenBetterLogger} from "./EvenBetterLogger";

@Component({
    selector: 'my-app',
    template: `
            <ul>
                <li *ngFor="let hero of heros"><span>{{hero.name}}</span>{{hero.age}}</li>
            </ul>
    `,
    providers:
        [ UserService , { provide: Logger, useClass: EvenBetterLogger }]
})
export class AppComponent {
    heros: Hero[];
    constructor(private userService: UserService) {
        this.heros = userService.getUsers();
    }
}
           
import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { AppComponent }  from './app.component';

@NgModule({
    imports: [
        BrowserModule,
    ],
    declarations: [
        AppComponent,
    ],
    bootstrap: [ AppComponent ]
})
export class AppModule { }
           
/**
 * Created by dell on 2016/9/13.
 */
import {Injectable} from '@angular/core';
import {Logger} from "./logger-service";

@Injectable()
export class EvenBetterLogger extends Logger {
    constructor() {
        super();
    }

    public log(message: string) {
        console.log("extend Logger content:" + message);
        super.log(`Base class content: ${message}`);
    }
}
           
export class Hero {
    id: number;
    name: string;
    isSecret = false;
}
           
import { Injectable } from '@angular/core';

@Injectable()
export class Logger {
    logs: string[] = [];

    log(message: string) {
        this.logs.push(message);
        console.log(message);
    }
}
           
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppModule } from './app.module';

platformBrowserDynamic().bootstrapModule(AppModule);
           
/**
 * Created by dell on 2016/9/13.
 */
import { Hero } from './hero';

export var HEROES: Hero[] = [
    { id: 11, isSecret: false, name: 'Mr. Nice' },
    { id: 12, isSecret: false, name: 'Narco' },
    { id: 13, isSecret: false, name: 'Bombasto' },
    { id: 14, isSecret: false, name: 'Celeritas' },
    { id: 15, isSecret: false, name: 'Magneta' },
    { id: 16, isSecret: false, name: 'RubberMan' },
    { id: 17, isSecret: false, name: 'Dynama' },
    { id: 18, isSecret: true,  name: 'Dr IQ' },
    { id: 19, isSecret: true,  name: 'Magma' },
    { id: 20, isSecret: true,  name: 'Tornado' }
];
           
/**
 * Created by dell on 2016/9/13.
 */
/**
 * Created by dell on 2016/9/8.
 */
import {Injectable} from '@angular/core';
import { HEROES }     from './mock-heroes';
import {Logger} from "./logger-service";

@Injectable()
export class UserService {

    constructor(private logger: Logger) {
    }

    getUsers() {
       this.logger.log('get users');
        return HEROES;
    }
}