我是angular2或编程的新手 我正在尝试使用github api通过用户名获取数据。
下面是我的文件。
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());
}
}
非常感谢您提前解决问题。
答案 0 :(得分:0)
您应该在AppModule提供程序中注入服务。
app.module.ts应该是:
@NgModule({
declarations: [
// the components
],
imports: [
// the modules to import
],
providers: [
GithubService
],
bootstrap: [AppComponent]
})
export class AppModule { }
答案 1 :(得分:0)
我犯了一个小错误 我在app.component.ts中导入了profile.component 它应该是GithubService
以下是当前的app.component.ts文件
import { Component } from '@angular/core';
import { GithubService } from './services/github.service';
@Component({
selector: 'my-app',
template: `<profile></profile>`,
providers: [GithubService]
})
export class AppComponent { }