2016-08-05 1 views
2

サービスを注入する私はAngular2を学ぶために始めたが、..私は私の成分を返すにサービスおよびインポートを作成しようとしましたが、私はこのエラーを取得:は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)); 

誰かが、なぜ私ができるアイデアを持っています」サービスを注入する?

答えて

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

は、そうでない場合は、それだけでパラメータだ、

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

privatepublicを追加すると、そのインスタンスのプロパティになりべきです。

+0

私はすでに試みましたが、私はこれを持っています:パラメータプロパティは、コンストラクタ実装でのみ許可されています。 –

+0

私は参照してください。それは妥当だと思う。コンストラクタは 'construct'ではなく' constructor'という名前にしてください;-) –

+0

Lol同じ問題。私は "コンストラクタ"という単語に文法エラーがありました:D – codepleb

1

あなたは依存関係を注入するときににアクセス修飾子を提供する必要があります。この

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

パラメータをプライベートに

これはあなたがアンダースコアを残すことができ、問題

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

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

    } 

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

を解決 使用して、それがプライベート変数のためだけの規約です。