Angular2 TS TS2322:类型'()=>任何'不能分配给'Post []'。

时间:2017-02-08 18:18:12

标签: angular typescript

githubrepo

我在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);
    }
}

console.log输出一个函数文字,而不是从REST API获取的预期帖子数组: enter image description here

1 个答案:

答案 0 :(得分:5)

在定义服务时使用类型,但真正的问题是res.json应为res.json()

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