M.Tanzil M.Tanzil - 5 months ago 36
AngularJS Question

How to call service in components in angular2

I am newbie to angular2, and i am working on a simple application where i want to call a Service Method

GetAuthors()
in a component, but somehow my service Method
GetAuthors()
is not calling. Everything works fine in component and shows up the result in browser but not the
service
part, i don't know what's the issue and What i am missing, Help me out.

Here is my code

app.component.ts

import { Component } from '@angular/core';
import {AuthorComponent} from './author.component';

@Component({
selector: 'my-app',
template: '<h1>Hello Angular!</h1><authors></authors>',
directives:[AuthorComponent]
})
export class AppComponent { }


author.component.ts

import {Component} from '@angular/core'
import {AuthorService} from './author.service'

@Component({
selector:"authors",
template:`
<h2>Author</h2>
<p>{{ title }}</p>
<ul>
<li *ngFor="#author of authors">{{ author }}</li>
</ul>
`,
})

export class AuthorComponent {
title = 'This is title for Author Component';
authors;
constructor(authorServie : AuthorService){
this.authors = authorServie.GetAuthors();
}
}


Here is my service
author.service.ts

export class AuthorService {
GetAuthors() : string[] {
return ["Author 1", "Author 2", "Author 3"];
}
}

Answer

To use your service in your component, you have to mark the service as injectable and add it into the component providers.

From the Angular documentation:

@Injectable() marks a class as available to an injector for instantiation. Generally speaking, an injector will report an error when trying to instantiate a class that is not marked as @Injectable().

I reccomend you to checkout this article about Angular`s Dependency injection.

author.service.ts

@Injectable() // <- Mark your service as injectable
export class AuthorService {
   GetAuthors() : string[] {
      return ["Author 1", "Author 2", "Author 3"];
   }    
}

author.component.ts

import {Component} from '@angular/core'
import {AuthorService} from './author.service'

@Component({
 selector:"authors",
 providers: [ AuthorService ], // <- Add your services here
 template:`
    <h2>Author</h2>
    <p>{{ title }}</p>
    <ul>
       <li *ngFor="#author of authors">{{ author }}</li>
    </ul>
 `,
 })

export class AuthorComponent {
  title = 'This is title for Author Component';
  authors;
  constructor(authorServie : AuthorService){
    this.authors = authorServie.GetAuthors();
  }
}

Let me know if you have any other problem with it. Cheers.