typescript – Angular 2服务未注入组件

前端之家收集整理的这篇文章主要介绍了typescript – Angular 2服务未注入组件前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我在Angular2(2.0.0-beta.0)应用程序中定义了一个服务.它是这样的:

import {Injectable} from "angular2/core";

@Injectable()
export class MyService {
    constructor() {

    }

    getSomething() {
        return 'something';
    }
}

我把它放在我的主应用程序文件中的bootstrap()函数中,以便它通常可用于我的代码

bootstrap(App,[MyService,SomeOtherService,ROUTER_DIRECTIVES[);

有时我不能在组件中使用该服务,即使我在组件构造函数()函数中有类似myService:MyService的东西,如下所示:

import {MyService} from '../services/my.service';

@Component({
    selector: 'my-component',directives: [],providers: [],pipes: [],template: `
    <div><button (click)="doStuff()">Click Me!</button></div>
    `
})
export MyComponent {
    constructor(myService:MyService) {} // note the private keyword

    doStuff() {
        return this.myService.getSomething();
    }
}

在其他地方它工作正常.在它不起作用的地方,我收到一条消息,如果我尝试访问它:

EXCEPTION: TypeError: Cannot read property 'getSomething' of undefined

它基本上意味着服务没有注入.

是什么导致它不被注射?

解决方法

这种行为完全正常.

在组件的构造函数方法中,当您不添加private或public关键字时,myService变量被计算为局部变量,因此它在方法调用结束时被销毁.

当您添加private或public关键字时,TypeScript会将该变量添加到class属性中,以便稍后使用此关键字调用属性.

constructor(myService: MyService) {
  alert(myService.getSomething());
  // This will works because 'myService',is declared as an argument
  // of the 'constructor' method.
}

doStuff() {
  return (this.myService.getSomething());
  // This will not works because 'myService' variable is a local variable
  // of the 'constructor' method,so it's not defined here.
}

猜你在找的Angularjs相关文章