簡體   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