Angular2:注入服务

时间:2016-08-05 14:27:13

标签: javascript service angular inject

我开始学习Angular2,但是..我试图在我的组件中创建一个服务并导入,但是我收到了这个错误:

  

错误TS2339:属性'commentService'在类型上不存在   'CommentsComponent'。

comment.service.ts

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


@Injectable()
export class CommentService {
    testfunction() {
        return 'valoare';
    }
}

comments.component.ts

import { Component, OnInit } from '@angular/core';
import { CommentService } from '../services/comment.service';

@Component({
  template: 'dadada',
  providers: [CommentService]
})

export class CommentsComponent implements OnInit {
    construct(commentService: CommentService) {
    }

    ngOnInit() { 
        console.log( this.commentService.testfunction() ); 
    }
}

app.component.ts

import { Component } from '@angular/core';
import { ROUTER_DIRECTIVES } from '@angular/router';

@Component({
  selector: '[web-application]',
  templateUrl: 'template/home',
  directives: [ROUTER_DIRECTIVES]
})
export class AppComponent { }

app.routes.ts

import { provideRouter, RouterConfig } from '@angular/router';
import { CommentsComponent } from './components/comments.component';
import { HomeComponent } from './components/home.component';

const routes: RouterConfig = [
  { path: '', component: HomeComponent },
  { path: 'comments', component: CommentsComponent }
];

export const appRouterProviders = [
  provideRouter(routes)
];

main.ts

import { bootstrap }    from '@angular/platform-browser-dynamic';
import { AppComponent } from './components/app.component';
import { appRouterProviders } from './app.routes';
import { CommentService } from './services/comment.service'

bootstrap(AppComponent, [
  appRouterProviders,
  CommentService
])
.catch(err => console.error(err));

有人知道为什么我不能注入这项服务?

3 个答案:

答案 0 :(得分:7)

export class CommentsComponent implements OnInit {
    construct(commentService: CommentService) {

应该是

export class CommentsComponent implements OnInit {
    constructor(private /* or public */ commentService: CommentService) {

添加privatepublic会使其成为实例属性,否则它只是一个参数。

答案 1 :(得分:1)

注入依赖项时,应提供访问修饰符。 使用此

export class CommentsComponent implements OnInit {
    constructor(private commentService: CommentService) {
}

答案 2 :(得分:0)

将参数设为私有

这解决了问题

@Component({
    template: 'dadada',
    providers: [CommentService]
})

export class CommentsComponent implements OnInit {
   constructor(private  _commentService: CommentService) {

   }

    ngOnInit() {
        console.log( this._commentService.testfunction() );
    }
}

你可以留下下划线,它只是私有变量的惯例。