加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

typescript – Angular 2服务未注入组件

发布时间:2020-12-17 18:01:49 所属栏目:安全 来源:网络整理
导读:我在Angular2(2.0.0-beta.0)应用程序中定义了一个服务.它是这样的: import {Injectable} from "angular2/core";@Injectable()export class MyService { constructor() { } getSomething() { return 'something'; }} 我把它放在我的主应用程序文件中的bootst
我在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.
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读