Search code examples
angularangular2-services

AppComponent.html:1 ERROR Error: No provider for GithubService


I am new in angular2 or in programming.
I am trying to get data by username using github api.

below are my files.

app.component.ts

import { Component } from '@angular/core';

import { ProfileComponent } from './components/profile.component';

@Component({
  selector: 'my-app',
  template: `<profile></profile>`,
})
export class AppComponent  { }

profile.component.ts

import {Component} from '@angular/core';

import {GithubService} from '../services/github.service';

@Component ({
    selector: 'profile',
    template: 'this is profilie page'
})

export class ProfileComponent{
    user: any;


    constructor(private _githubServie: GithubService){
        this._githubServie.getUser().subscribe(user => {
            console.log(user);
            this.user = user;
        })
    }
}

github.service.ts

import {Injectable} from '@angular/core';
import {Http, Headers} from '@angular/http';

import 'rxjs/add/operator/map';

@Injectable()

export class GithubService{

    private username: string;
    private client_id = "xxxxxxxxxxxxx";
    private client_secret = "xxxxxxxxxxxxxxxxxxxxxxxxx";

    constructor( private _http: Http){
        console.log("github service is ready");
        this.username = "graphicsmanoj";
    }

    getUser(){
        return this._http.get('http://api.github.com/users/'+this.username+'?client_id='+this.client_id+'&client_secret='+this.client_secret).map(res => res.json());
    }
}

Thank you very much in advance for the solution.


Solution

  • You should inject the service in the AppModule providers.

    The app.module.ts should be like :

    @NgModule({
      declarations: [
        // the components
    ],
      imports: [
        // the modules to import
      ],
      providers: [
        GithubService
      ],
      bootstrap: [AppComponent]
    })
    export class AppModule { }