Krishnan
Krishnan

Reputation: 1008

angular2 service method not getting invoked

I tried to create a sample angular2 service and consume it, but I am not sure about the mistake that i have done. the service method couldn't be called by the component, Please see the plunker for more details https://plnkr.co/edit/tlnGU9Er6GxsOaUMCZZG?p=preview

My service code looks like below

import { Injectable } from 'angular2/core';
import { HTTP_PROVIDERS, Http, Headers, Response, JSONP_PROVIDERS, Jsonp } from 'angular2/http';
import { Configuration } from './Configuration';
import 'rxjs/add/operator/map'
import { Observable } from 'rxjs/Observable';

///Service class to call REST API
@Injectable()
export class SampleService {
    items: Array<any>;

    constructor() {
        this.items = [
            { name: 'Test1' },
            { name: 'Test2' },
            { name: 'Test3' }
        ];
    }

    getItems() {
        return this.items;
    }
}

Upvotes: 1

Views: 5447

Answers (1)

Denko Mancheski
Denko Mancheski

Reputation: 2719

You need to include the @Injectable service in the array of providers when you bootstrap the app (in your case bootstrap(SampleComponent, [SampleService])) or inside the providers array in the component. More on Dependency injection you can read here: https://angular.io/docs/ts/latest/guide/dependency-injection.html.

After you add it as a provider, whenever you inject it in the class constructor, the component will be able to resolve it. It will be clear how the tree of dependency injection works after you read that link :)

Also in the plunkr you have two components with the same selector ('my-app') which I guess is also a mistake.

Upvotes: 1

Related Questions