AppComponent.html:1 ERROR TypeError:无法读取undefined的属性'subcribe'

时间:2017-05-11 04:50:39

标签: angularjs node.js angular2-services

您好我是AngularJs 2的新手。

我正在创建简单的应用程序来读取Github API。

当我使用以下文件启动应用程序时,我收到以下错误:

AppComponent.html:1错误TypeError:无法读取未定义的属性'subcribe'

以下是我的服务和组件ts文件。

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 = "client_id";
    private client_secret = "client_secret";

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

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

profile.component.ts

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

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

@Component({
    moduleId: module.id,
    selector: 'profile',
    templateUrl: 'profile.component.html',
})
export class ProfileComponent  {
    constructor(private _githubService: GithubService){
        this._githubService.getUser().subcribe(user => {
            console.log(user);
        })
    }
}

非常感谢您提供的解决方案。

2 个答案:

答案 0 :(得分:0)

它应该是 subscribe

更改为

this._githubService.getUser().subscribe(user => {
            console.log(user);
})

并将您的服务更改为

  getUser(): Observable<any> {
       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());
    }

答案 1 :(得分:0)

GithubService中,您需要返回this._http.get的结果。

@Injectable()
export class GithubService{
    ...

    getUser(): Observable<any> {
        // return was missing
        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());
    }
}