来自Github API的Angular 2 HTTP GET请求

时间:2017-05-10 00:01:50

标签: api angular http typescript github

我是Angular 2的新手。至于现在,我正在尝试从Github API获取用户数据。我有一个组件(user.component),这是它的代码:

import {Component} from '@angular/core';
import {userService} from './user.service';
import'rxjs/add/operator/map';

@Component({
    selector: 'users',
    template: `
    <h2>Users</h2>
    `,
    providers: [userService]
})
export class UserComponent{

    constructor(private _userService: userService) 
    {
       this._userService.getUser().subscribe( user => {console.log(user)})
    }

}

user.Service.ts 的代码:

import {Injectable} from '@angular/core'
import {Http, Headers} from '@angular/http'
import'rxjs/add/operator/map';

@Injectable()

export class userService{
    private username : string;

    constructor (private _http:Http){
        console.log("Github Service is ready...")
        this.username = "example"
    }
    getUser(){
        return this._http.get("http://api.github.com/users/"+example)
        .map(res => res.json)
    }
}

这是 app.module.ts

import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { UserComponent } from './user.component'
import {HttpModule } from '@angular/http';
import { AppComponent }  from './app.component';

@NgModule({
  imports:      [ BrowserModule, HttpModule ],
  declarations: [ AppComponent,UserComponent ],
  bootstrap:    [ AppComponent ]
})
export class AppModule { }

最后这里是 app.component.ts

import { Component } from '@angular/core';
import { UserService } from './user.service'

@Component({
  selector: 'my-app',
  template: `<h1>Hello {{name}}</h1><users></users>`,
  providers: [CourseService]
})
export class AppComponent  { name = 'John'; }

2 个答案:

答案 0 :(得分:0)

您应该将providers: [CourseService]添加到模块,而不是应用程序组件。

@NgModule({
  imports:      [ BrowserModule, HttpModule ],
  declarations: [ AppComponent,UserComponent ],
  bootstrap:    [ AppComponent ],
  providers:    [ CourseService ]
})

并将其从@Component装饰器中删除。

编辑:我很高兴你有这个工作,但评论者是对的 - 这不是一个正确的解决方案,我错了。

答案 1 :(得分:0)

example不是getUser()

中的局部变量

我认为你打算写的是:

getUser(){
        return this._http.get("http://api.github.com/users/" + this.username)
        .map(res => res.json)
}