Search code examples
javascriptserviceangularinject

Angular2: Injecting a service


I started to learn Angular2, but.. I tried to create a service and import in my compoment, but I get this error:

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));

Somebody have an idea why I can't inject the service?


Solution

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

    should be

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

    Adding private or public makes it an instance property, otherwise it's just a parameter.