Angular2:注入服务

Geo*_*tin 2 javascript service inject angular

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

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

comment.service.ts

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


@Injectable()
export class CommentService {
    testfunction() {
        return 'valoare';
    }
}
Run Code Online (Sandbox Code Playgroud)

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() ); 
    }
}
Run Code Online (Sandbox Code Playgroud)

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 { }
Run Code Online (Sandbox Code Playgroud)

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)
];
Run Code Online (Sandbox Code Playgroud)

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));
Run Code Online (Sandbox Code Playgroud)

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

Gün*_*uer 7

export class CommentsComponent implements OnInit {
    construct(commentService: CommentService) {
Run Code Online (Sandbox Code Playgroud)

应该

export class CommentsComponent implements OnInit {
    constructor(private /* or public */ commentService: CommentService) {
Run Code Online (Sandbox Code Playgroud)

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

  • 我知道了.这听起来很合理.构造函数应该命名为`constructor`而不是`construct`尽管;-) (2认同)
  • 哈哈同样的问题!我拼错了"contructor"..等等.我刚刚再做一次!:( (2认同)