I'm trying to get post data using http service in angular 2. and dont understand what wrong I'm doing here..
I'm using Plunker here
I've console.logged and it is showing this error. How to solve this this undefined?
Error:
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());
}
}
Here is plunker - https://plnkr.co/edit/jWaPbNlqsqXoOFFRzhhX?p=preview