我正在角上工作,在ngOnInit函数中输入void错误

时间:2019-03-03 07:55:44

标签: angular

import { Component, OnInit, OnDestroy } from "@angular/core";
import { Subscription } from 'rxjs';

import { Post } from "../post.model";
import { PostsService } from "../posts.service";

@Component({
  selector: "app-post-list",
  templateUrl: "./post-list.component.html",
  styleUrls: ["./post-list.component.css"]
})
export class PostListComponent implements OnInit, OnDestroy {
  // posts = [
  //   { title: "First Post", content: "This is the first post's content" },
  //   { title: "Second Post", content: "This is the second post's content" },
  //   { title: "Third Post", content: "This is the third post's content" }
  // ];
  posts: Post[] = [];
  private postsSub: Subscription;

  constructor(public postsService: PostsService) {}

  ngOnInit() {
   this.posts = this.postsService.getPosts();
    this.postsSub = this.postsService.getPostUpdateListener()
      .subscribe((posts: Post[]) => {
        this.posts = posts;
      });
  }enter code here

  ngOnDestroy() {
    this.postsSub.unsubscribe();
  }
}

我遇到错误

"Type 'void' is not assignable to type 'Post[]'.ts(2322)
(property) PostListComponent.posts: Post[]". in ngOnInit function.  Type 'void' is not assignable to type 'Post[]'

1 个答案:

答案 0 :(得分:0)

看起来PostsService.getPosts()返回了void,而不是Post[]

因此,请在您的PostsService类中进行检查。

它应该像这样:

getPosts(): Post[] {
  // implementation
}