Angular2:注入服务

Angular2: Injecting a service

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

error TS2339: Property 'commentService' does not exist on type '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) {
}

在打字稿中,可以隐式或显式地声明和实例化属性。

隐式声明 通过向每个 属性 添加访问修饰符将属性传递给构造函数,而不在构造函数中实现任何内容。

constructor(private commentService:CommentService) {}

class 将有一个名为 commentService 的 属性 具有私有访问修饰符。

显式声明和初始化声明class属性,然后在构造函数中用传递给构造函数的值初始化它们。

class Component {
  private commentService: CommentService;
 
  constructor(comentService: CommentService) {
    this.commentService = commentService;
  }
}

所以你所做的就是将一个参数传递给构造函数并且根本没有使用它加上 class 没有声明 属性。所以 class 根本没有 commentService 属性。您应该向构造函数的参数添加访问修饰符并隐式声明它,或者自己在 class 中将其声明为 class 属性 并显式初始化它。