TypeError:无法读取未定义的属性'getPosts'

时间:2017-01-13 21:26:12

标签: angular

我正在尝试使用角度为2的http服务发布数据。并且不明白我在这里做了什么错... 我在这里使用Plunker 我已经安装了console.logged,它显示了这个错误。如何解决这个未定义?

错误:

ZoneAwareError
message
:"(SystemJS) TypeError: Cannot read property 'getPosts' of undefined↵ 
at execute     
(https://run.plnkr.co/YV2OxH7SpFuwfVbA/src/app.ts!transpiled:48:30)↵        
at ZoneDelegate.invoke  
(https://unpkg.com/zone.js@0.7.5/dist/zone.js:242:26)↵      at 
Zone.run (https://unpkg.com/zone.js@0.7.5/dist/zone.js:113:43)↵     at 
https://unpkg.com/zone.js@0.7.5/dist/zone.js:535:57↵        at 
ZoneDelegate.invokeTask 
(https://unpkg.com/zone.js@0.7.5/dist/zone.js:275:35)↵      at 
 Zone.runTask (https://unpkg.com/zone.js@0.7.5/dist/zone.js:151:47)↵        
at drainMicroTaskQueue 
(https://unpkg.com/zone.js@0.7.5/dist/zone.js:433:35)↵  Error loading  
 https://run.plnkr.co/YV2OxH7SpFuwfVbA/src/main.ts"
 name
 :
 "Error"

app.ts

//our root app component
import {Component, NgModule} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'
import {HttpModule} from '@angular/http';
import {PostsService} from './posts';

@Component({
  selector: 'my-app',
  template: `
    <h3>Posts</h3>
    <div *ngFor="let post of posts | async">
        <h3>{{post.title}}</h3>
        <p>{{post.body}}</p>
    </div>
  `,
  providers: [PostsService]

})
export class App {
  posts:Post[];
  constructor(private postsService: PostsService) {
    this.name = 'Angular2'
  }

  this.postsService.getPosts().subscribe(posts => {
  this.posts = posts;
}

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

interface Post{
    id: number;
    title: string;
    body: string;
}

posts.ts

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

@Injectable()
export class PostsService {
    constructor(private http: Http){
        console.log('PostsService Initialized...');
    }

    getPosts(){
    return this.http.get('https://jsonplaceholder.typicode.com/posts')
            .map(res => res.json());
    }
}

这是plunker - https://plnkr.co/edit/jWaPbNlqsqXoOFFRzhhX?p=preview

2 个答案:

答案 0 :(得分:2)

Sushant,

您需要订阅方法正文 - 您将放置代码的当前位置作为声明,并在实例化服务之前对其进行操作。

您有几种选择,一种是:

import {OnInit} from '@angular/core'
...
export class App implements OnInit {
  posts:Post[];
  constructor(private postsService: PostsService) {
    this.name = 'Angular2'
  }

  ngOnInit(){
    this.postsService.getPosts().subscribe(posts => {
      this.posts = posts;
    }
}

在实例化组件时,OnInit被称为生命周期钩子,因此您可以参考“直播”。在这里可以观察到。

考虑关于生命周期钩子的Angular 2文档的这个链接: https://angular.io/docs/ts/latest/guide/lifecycle-hooks.html

答案 1 :(得分:-1)

试试这个:

constructor(private postsService: PostsService) {
  this.postsService.getPosts().subscribe(posts => {
    console.log(posts);
    this.posts = posts;
  }
}