我在CLI控制台中遇到上述错误,即使已将Post定义为接口/类型: user.component.ts:
import { Component } from '@angular/core';
import {PostService} from '../services/post.service';
@Component({
selector: 'user',
template: #`,
providers: [PostService],
})
export class UserComponent {
name: string;
email: string;
address: address;
hobbies: string[];
showhobbies: boolean;
posts: Post[];
` constructor(private postService: PostService) {
...
this.postService.getPosts().subscribe(posts => {
this.posts = posts;
console.log(posts);
});
}
}
interface Post{
id: number;
title: string;
body: string;
}
post.service.js:
import {Injectable} from '@angular/core';
import {Http} from '@angular/http';
import 'rxjs/add/operator/map';
@Injectable()
export class PostService {
constructor(private http: Http){
console.log("PostService initialized");
}
getPosts(){
return this.http.get('https://jsonplaceholder.typicode.com/posts')
.map(res => res.json);
}
}
答案 0 :(得分:5)
在定义服务时使用类型,但真正的问题是res.json
应为res.json()
:
getPosts(): Observable<Post[]> {
return this.http.get('https://jsonplaceholder.typicode.com/posts')
.map(res => res.json());
}