加载页面时 Observable 数组为空但稍后有内容?

Array of Observable is empty when loading the page but has content later on?

我正在尝试实现 ngx-infinite-scroll。我想从我的“posts”数组中取出前 5 个帖子,并在开始时将它们放入“shownPosts”数组中,然后当用户继续向下滚动时,我希望它添加另外 5 个,但我 运行 进入问题是我的“帖子”数组是空的,而侧面仍在加载 (ngOnInit)。

如果我稍后用另一个函数 (checkPosts) 检查数组,它会得到所有的帖子。这是为什么?

网站加载时的控制台日志:

In constructor, this.posts.length: 0
In ngOnInit, this.posts.length: 0
ERROR TypeError: Cannot read properties of undefined (reading 'title')       core.mjs:6485 
    at HotComponent.ngOnInit (hot.component.ts:37:70)
    at callHook (core.mjs:2542:1)
    at callHooks (core.mjs:2511:1)
    at executeInitAndCheckHooks (core.mjs:2462:1)
    at refreshView (core.mjs:9499:1)
    at refreshComponent (core.mjs:10655:1)
    at refreshChildComponents (core.mjs:9280:1)
    at refreshView (core.mjs:9534:1)
    at refreshEmbeddedViews (core.mjs:10609:1)
    at refreshView (core.mjs:9508:1)

网站加载后,我 运行 通过按钮“checkPosts()”后的控制台日志:

In checkPosts, this.posts.length: 32
In checkPosts, this.posts[0].title: This is the first posts title.

hot.component.ts:

import ...

@Component({
...
})

export class HotComponent implements OnInit {
  posts: Post[] = [];
  shownPosts: Post[] = [];
  normalDrawerShown: boolean = true;
  subscription!: Subscription;
...

constructor(private postService: PostService, private uiService: UiService) {
  this.subscription = this.uiService
  .onToggleNormalDrawer()
  .subscribe((value) => (this.normalDrawerShown = value));

  console.log("In constructor, this.posts.length: "+ this.posts.length);
}

ngOnInit(): void {
  this.postService.getPosts().subscribe((posts) => (this.posts = posts));

  console.log("In ngOnInit, this.posts.length: "+ this.posts.length);
  console.log("In ngOnInit, this.posts[0].title: " + this.posts[0].title);
}

checkPosts():void{
  console.log("In checkPosts, this.posts.length: "+ this.posts.length);
  console.log("In checkPosts, this.posts[0].title: " + this.posts[0].title);
}
...
}

Post.ts:

export interface Post {
  id?: number;
  title: string;
  fileName: string;
  url: string;
  section: string;
  postTime: string;
  upvotes: number;
  downvotes: number;
  comments: number;
}

post.service.ts:

getPosts():Observable<Post[]> {
  return this.http.get<Post[]>(this.apiUrl);
}

向后端发送 Http 请求api 需要时间。

这行代码:

this.postService.getPosts().subscribe((posts) => (this.posts = posts));

...意味着当 observable created here:

this.http.get<Post[]>(this.apiUrl);

...发出值(因此当 http 请求 return 某个值时)然后获取该值并将其分配给 this.posts。由于 http 请求需要一些时间,因此当您在订阅后立即尝试 console.log 它时,该值不会显示。