在Angular组件上初始化变量

时间:2019-01-07 13:11:02

标签: angular angular6 angular-components angular7

在Angular 7组件上,我具有以下内容:

export class PostListComponent implements OnInit {

  posts: PostModel[] = [];

  constructor(private postService: PostService) { }

  ngOnInit() {

    this.posts = this.getPosts();

  }

  getPosts(): PostModel[] {

    let posts: PostModel[] = [];

    posts = postService.getTopPosts();

    return posts;

  }

}

我应该在getPosts()方法中设置this.posts吗?

还是我应该像在做的那样返回帖子并在ngOnInit中设置this.posts?

有没有更好的方法初始化Angular组件上的变量?

1 个答案:

答案 0 :(得分:1)

That's look better:

export class PostListComponent implements OnInit {

  posts: PostModel[] = [];

  constructor(private postService: PostService) { }

  ngOnInit() {
    this.posts = this.getPosts();
  }

  getPosts(): PostModel[] {
    return this.postService.getTopPosts();
  }

}

I personally do this logic aswell and, in a big project, it helps cleaning out what is going on when you have thousands of lines.