AppComponent.html:1 ERROR TypeError: Cannot read property 'subcribe' of undefined

AppComponent.html:1 ERROR TypeError: Cannot read property 'subcribe' of undefined

嗨,我是 AngularJs 2.

的新手

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

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

AppComponent.html:1 错误类型错误:无法读取未定义的 属性'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);
        })
    }
}

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

应该是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());
    }

在您的 GithubService 中,您需要 return 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());
    }
}