【问题标题】:AppComponent.html:1 ERROR TypeError: Cannot read property 'subcribe' of undefinedAppComponent.html:1 错误类型错误:无法读取未定义的属性“订阅”
【发布时间】:2017-05-11 04:50:38
【问题描述】:

您好,我是 AngularJs 2 的新手。

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

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

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

以下是我的服务和组件 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);
        })
    }
}

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

【问题讨论】:

  • @Momin 请记住,当您过去代码时,请删除敏感信息,例如 client_id 和 client_secret。我现在已经为你删除了,但请记住这一点。
  • 好的!但我在哪里做呢?
  • @Momin 您在此问题中编写的代码包含“client_id”和“client_secret”。写问题时要小心,不要包含任何敏感信息。我建议你去github.com/settings/tokens删除旧的并创建一个新的。

标签: angularjs node.js angular2-services


【解决方案1】:

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

【讨论】:

  • 嗨 Sajeetharan,感谢您的重播。添加代码时,此处拼写错误。即使订阅也是错误的。
  • 它在我的代码编辑器中显示为红色下划线。当我将鼠标悬停时,它显示以下消息。 [ts] 类型 'void' 上不存在属性 'subscribe'。
  • 将 getservice 中的方法更改为 getUser(): Observable
  • 错误类型错误:无法读取控制台中未定义的属性“订阅”
  • 你能告诉我什么是 Observable
【解决方案2】:

在您的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());
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-08
    • 2017-04-13
    • 2018-04-29
    相关资源
    最近更新 更多