2016-08-05 212 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

我明白了。這聽起來很合理。雖然;構造函數應該被命名爲'constructor'而不是'construct'' –

+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()); 
    } 
} 

你可以離開下劃線,它只是一個私有變量約定。