繁体   English   中英

Angular2:注入服务

[英]Angular2: Injecting a service

我开始学习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));

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

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

应该

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

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

注入依赖项时应该提供访问修饰符 用这个

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

将参数设为私有

这解决了这个问题

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

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

   }

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM