2017-05-11 117 views
1

喜的特性“SUBCRIBE”我是新来AngularJs 2.AppComponent.html:1错误类型错误:无法读取未定义

我创建简单的应用程序来读取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); 
     }) 
    } 
} 

非常感谢您提前给出的解决方案。

+0

@Momin请记住,当你过去的代码,删除像client_id和client_secret这样的敏感信息。我现在已经为你删除了这个,但是请记住这个。 – fredrik

+0

好的!但我在那里做? – Momin

+0

@Momin你在这个问题中写的代码包含“client_id”和“client_secret”。当你写问题时不要包含任何敏感信息时请小心。我建议你去https://github.com/settings/tokens并删除旧的并创建一个新的。 – fredrik

回答

0

这shoulb是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()); 
    } 
+0

嗨Sajeetharan,谢谢你的重播。在添加代码时,这里是拼写错误。即使订阅也是错误。 – Manoj

+0

错误是什么? – Sajeetharan

+0

它在我的代码编辑器中以红色下划线显示。当我将鼠标悬停时,它显示以下消息。 [ts]在'void'类型中不存在属性'subscribe'。 – Manoj

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()); 
    } 
} 
+0

非常感谢Fredrik。它为我工作 – Manoj

相关问题