Angular2 RC.1注射

时间:2016-06-08 14:55:12

标签: angular typescript angular2-services

我目前正在学习Angular2,问题是每次我找到一个好的教程时它都会改变(并且它不适合最新的Angular2版本)。

无论如何 - 我试图将服务从一个文件注入另一个文件,但不能重复教程中的人。

以下是教程的链接:https://egghead.io/lessons/angular-2-injecting-a-service

./ main.ts

import {bootstrap} from '@angular/platform-browser-dynamic';
import {Component} from "@angular/core";
import {TodoInput} from './todo-input';
import {TodoService} from "./todo-service";

@Component({
    selector: 'my-app',
    directives: [TodoInput],
    template: '<div><todo-input></todo-input></div>'
})

class App{}

bootstrap(App, [TodoService]);

./待办事项-service.ts

import {Injectable} from "@angular/core";

@Injectable()

export class TodoService {
    todos:string[] = [];
}

./待办事项-input.ts

import {Component} from "@angular/core";
import {TodoService} from "./todo-service";

@Component({
    selector: 'todo-input',
    template: `<div>
    I'm a todo input
    <input type="text" #myInput>
    <button (mouseover)="onClick($event, myInput.value)">Click me</button>
    </div>`
})

export class TodoInput{
    constructor(todoService:TodoService) {
        console.log(todoService);
    }

    onClick(event, value) {
        console.log(event, value);
    }
}

我在控制台中有这个:

  

EXCEPTION:TypeError:无法读取属性&#39;查询&#39;为null   platform-b​​rowser.umd.js:962 EXCEPTION:TypeError:无法读取属性   &#39;查询&#39; of nullBrowserDomAdapter.logError @   platform-b​​rowser.umd.js:962BrowserDomAdapter.logGroup @   platform-b​​rowser.umd.js:972ExceptionHandler.call @   core.umd.js:3696(匿名函数)@   core.umd.js:8982ZoneDelegate.invoke @   zone.js:323NgZoneImpl.inner.inner.fork.onInvoke @   core.umd.js:6075ZoneDelegate.invoke @ zone.js:322Zone.run @   zone.js:216(匿名函数)@ zone.js:571ZoneDelegate.invokeTask @   zone.js:356NgZoneImpl.inner.inner.fork.onInvokeTask @   core.umd.js:6066ZoneDelegate.invokeTask @ zone.js:355Zone.runTask @   zone.js:256drainMicroTaskQueue @ zone.js:474ZoneTask.invoke @   zone.js:426 platform-b​​rowser.umd.js:971EXCEPTION:错误:未捕获(在   promise):TypeError:无法读取属性&#39;查询&#39;为null   platform-b​​rowser.umd.js:962EXCEPTION:错误:未捕获(在承诺中):   TypeError:无法读取属性&#39;查询&#39;的   nullBrowserDomAdapter.logError @   platform-b​​rowser.umd.js:962BrowserDomAdapter.logGroup @   platform-b​​rowser.umd.js:972ExceptionHandler.call @   core.umd.js:3696(匿名函数)@ core.umd.js:8951schedulerFn @   core.umd.js:6007SafeSubscriber .__ tryOrUnsub @   Subscriber.ts:240SafeSubscriber.next @   Subscriber.ts:192Subscriber._next @ Subscriber.ts:133Subscriber.next @   Subscriber.ts:93Subject._finalNext @ Subject.ts:154Subject._next @   Subject.ts:144Subject.next @ Subject.ts:90EventEmitter.emit @   core.umd.js:5996NgZone._zoneImpl.NgZoneImpl.onError @   core.umd.js:6227NgZoneImpl.inner.inner.fork.onHandleError @   core.umd.js:6096ZoneDelegate.handleError @ zone.js:327Zone.runGuarded   @ zone.js:233_loop_1 @ zone.js:487drainMicroTaskQueue @   zone.js:494ZoneTask.invoke @ zone.js:426   platform-b​​rowser.umd.js:962STACKTRACE:BrowserDomAdapter.logError @   platform-b​​rowser.umd.js:962ExceptionHandler.call @   core.umd.js:3698(匿名函数)@ core.umd.js:8951schedulerFn @   core.umd.js:6007SafeSubscriber .__ tryOrUnsub @   Subscriber.ts:240SafeSubscriber.next @   Subscriber.ts:192Subscriber._next @ Subscriber.ts:133Subscriber.next @   Subscriber.ts:93Subject._finalNext @ Subject.ts:154Subject._next @   Subject.ts:144Subject.next @ Subject.ts:90EventEmitter.emit @   core.umd.js:5996NgZone._zoneImpl.NgZoneImpl.onError @   core.umd.js:6227NgZoneImpl.inner.inner.fork.onHandleError @   core.umd.js:6096ZoneDelegate.handleError @ zone.js:327Zone.runGuarded   @ zone.js:233_loop_1 @ zone.js:487drainMicroTaskQueue @   zone.js:494ZoneTask.invoke @ zone.js:426   platform-b​​rowser.umd.js:962错误:未捕获(在promise中):TypeError:   无法阅读属性&#39;查询&#39;为null       at resolvePromise(zone.js:538)       在PromiseCompleter.reject(zone.js:515)       在eval(core.umd.js:8981)       在ZoneDelegate.invoke(zone.js:323)       at Object.NgZoneImpl.inner.inner.fork.onInvoke(core.umd.js:6075)       在ZoneDelegate.invoke(zone.js:322)       在Zone.run(zone.js:216)       在zone.js:571       在ZoneDelegate.invokeTask(zone.js:356)       at Object.NgZoneImpl.inner.inner.fork.onInvokeTask(core.umd.js:6066)BrowserDomAdapter.logError @   platform-b​​rowser.umd.js:962ExceptionHandler.call @   core.umd.js:3699(匿名函数)@ core.umd.js:8951schedulerFn @   core.umd.js:6007SafeSubscriber .__ tryOrUnsub @   Subscriber.ts:240SafeSubscriber.next @   Subscriber.ts:192Subscriber._next @ Subscriber.ts:133Subscriber.next @   Subscriber.ts:93Subject._finalNext @ Subject.ts:154Subject._next @   Subject.ts:144Subject.next @ Subject.ts:90EventEmitter.emit @   core.umd.js:5996NgZone._zoneImpl.NgZoneImpl.onError @   core.umd.js:6227NgZoneImpl.inner.inner.fork.onHandleError @   core.umd.js:6096ZoneDelegate.handleError @ zone.js:327Zone.runGuarded   @ zone.js:233_loop_1 @ zone.js:487drainMicroTaskQueue @   zone.js:494ZoneTask.invoke @ zone.js:426 zone.js:461未处理的承诺   拒绝:无法读取属性&#39;查询&#39;无效;区域:角;   任务:Promise.then;值:TypeError:无法读取属性&#39;查询&#39;的   null(...)consoleError @ zone.js:461_loop_1 @   zone.js:490drainMicroTaskQueue @ zone.js:494ZoneTask.invoke @   zone.js:426 zone.js:463错误:未捕获(在承诺中):TypeError:   无法阅读属性&#39;查询&#39; of null(...)consoleError @   zone.js:463_loop_1 @ zone.js:490drainMicroTaskQueue @   zone.js:494ZoneTask.invoke @ zone.js:426

但是变化很小,它开始工作:

./待办事项-input.ts

import {Component} from "@angular/core";
import {TodoService} from "./todo-service";

@Component({
    selector: 'todo-input',
    template: `<div>
    I'm a todo input
    <input type="text" #myInput>
    <button (mouseover)="onClick($event, myInput.value)">Click me</button>
    </div>`
})

export class TodoInput{
    constructor() {
        console.log(TodoService);
    }

    onClick(event, value) {
        console.log(event, value);
    }
}

我在控制台中有正常的对象(没有任何错误

SystemJS config

<script>
    (function(global) {
        // map tells the System loader where to look for things
        var map = {
            'app':                        'app', // 'dist',
            '@angular':                   '@angular',
            'angular2-in-memory-web-api': 'angular2-in-memory-web-api',
            'rxjs':                       'rxjs'
        };
        // packages tells the System loader how to load when no filename and/or no extension
        var packages = {
            'app':                        { main: 'main.js',  defaultExtension: 'js' },
            'rxjs':                       { defaultExtension: 'js' },
            'angular2-in-memory-web-api': { main: 'index.js', defaultExtension: 'js' },
        };
        var ngPackageNames = [
            'common',
            'compiler',
            'core',
            'http',
            'platform-browser',
            'platform-browser-dynamic',
            'router',
            'router-deprecated',
            'upgrade',
        ];
        // Individual files (~300 requests):
        function packIndex(pkgName) {
            packages['@angular/'+pkgName] = { main: 'index.js', defaultExtension: 'js' };
        }
        // Bundled (~40 requests):
        function packUmd(pkgName) {
            packages['@angular/'+pkgName] = { main: pkgName + '.umd.js', defaultExtension: 'js' };
        };
        // Most environments should use UMD; some (Karma) need the individual index files
        var setPackageConfig = System.packageWithIndex ? packIndex : packUmd;
        // Add package entries for angular packages
        ngPackageNames.forEach(setPackageConfig);
        var config = {
            baseURL: '{!! url('public/admin/js') !!}',
            map: map,
            packages: packages
        }
        System.config(config);
    })(this);

    System.import('app').catch(function(err){ console.error(err); });
</script>

所以我的问题是:为什么我不能在构造函数参数中调用该服务,因为它在教程中完成了?或者怎么做?我错过了什么吗?教程似乎真的很棒,可以给我非常好的Angular2基础知识,但是当你坚持这样简单的事情时,它很难学习。

非常感谢! 汤姆

1 个答案:

答案 0 :(得分:0)

让它排序。与PHPStorm一起提供的TypeScript编译器导致了这些问题。我已经设置了我的 tsconfig.json 文件并通过 npm tsc 运行它,现在它正在运行。

<强> tsconfig.json

{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "moduleResolution": "node",
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "removeComments": false,
    "noImplicitAny": false,
    "outDir": "./public/admin/js/app"
  },
  "exclude": [
    "node_modules",
    "build",
    "vendor",
    "public"
  ]
}

只是认为我仍然不确定如何从日志中删除这些来自排除文件夹的编译错误。

干杯!