Is it normal for the Array of Observables to be empty upon initial page load, only to contain content later

Currently, I am working on integrating ngx-infinite-scroll functionality. My goal is to extract the initial 5 posts from my "posts" array and populate them into the "shownPosts" array at the beginning. Subsequently, as the user continues scrolling down, I intend to add another set of 5 posts. However, I encountered an issue where my "posts" array appears empty while the site is still loading in the ngOnInit.

The peculiarity arises when, upon posterior inspection with a different function (checkPosts), all the Posts are present. What could be causing this discrepancy?

Upon loading the website, the console outputs the following:

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)

After manually triggering the "checkPosts()" function through a button once the site has loaded, the console logs display:

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

Answer №1

Sometimes, HTTP requests to the backend API can take a bit of time.

In this particular line of code:

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

...what it means is that when the observable is created in this section:

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

...it will emit a value once the HTTP request receives a response. This value is then assigned to this.posts. However, because HTTP requests do take some time, you may not see this value immediately if you try to log it right after subscribing.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

A guide to teaching TypeScript to automatically determine the type of dynamic new() calls

One of the challenges I'm facing involves dynamically creating subclasses and ensuring that the factory function is aware of the subclass's return type. While I can currently achieve this using a cast, I am exploring options to infer the return ...

The parameter type 'Object' cannot be assigned to the parameter type 'string'

Everything seems to be working fine in my application, but I am encountering the following error message: The argument of type 'Object' is causing an issue and cannot be assigned to a parameter of type 'string' Here is the code snip ...

Error: Local variable remains undefined following an HTTP request

Whenever I make http calls, my goal is to store the received JSON data in a local variable within my component and then showcase it in the view. Service: getCases(){ return this.http.get('someUrl') .map((res: Response) => res.jso ...

A class in Typescript containing static methods that adhere to an interface with a string index

Take a look at this code snippet: interface StringDoers { [key: string]: (s: string) => void; } class MyStringDoers implements StringDoers { public static print(s: string) { console.log(s); } public static printTwice(s: string) { conso ...

What is the reason for user.id being set as a 'string' by default?

Currently, I am in the process of creating a Next Auth system using TypeScript, and I have encountered a type issue related to the 'user.id' data. This error is specifically happening in the callbacks section. The types of 'user.id' ar ...

Obtain a filtering dropdown list directly from the database within Ag-grid

Currently in my interface, I am attempting to implement a filter for the FOLDER column. This filter is supposed to retrieve data from the database and present it in a dropdown checkbox within that column. The filtering should be based on the selected data. ...

I'm having difficulty updating the Angular CLI version

I am currently running Angular CLI version 7.1.4 and I have been attempting to update to the latest version. However, each time I try to update, I encounter a multitude of errors. I have attempted using the command ng update @angular/core @angular/cli b ...

Learn how to efficiently import data into d3.js from several JavaScript arrays, and create a dynamically updating chart without the need to refresh the page

I currently have two arrays: one is a list of numbers called nums, and the other is a list of strings titled places. For example: nums=[1,2,3,4,5] places = ["house","gym", "work", "school", "park"] Both arrays are the same length. I am looking to crea ...

Is there a way to modify the default lite-server port in the Angular quickstart setup?

I recently obtained the Angular 4 quickstart app and decided to modify the default lite-server port by including "port": 8000 in bs-config.json like this: { "server": { "port": 8000, "baseDir": "src", "routes": { "/node_modules": "node ...

Issue with nestjs build due to ts-loader module in dev-dependency

I've encountered a Module Error with ts-loader during a docker build ERROR [6/6] RUN nest build 3.9s ------ > [6/6] RUN ...

Filter an array of objects recursively based on various properties

I need help filtering an object with nested arrays based on specific criteria. Specifically, I want to filter the main array by matching either RazaoSocial:"AAS" or Produtos:[{Descricao:"AAS"}] This is my code: var input = [ { RazaoSocial: 'AA ...

How can you ensure an interface in typescript 3.0 "implements" all keys of an enum?

Imagine I have an enum called E { A = "a", B = "b"}. I want to enforce that certain interfaces or types (for clarity, let's focus on interfaces) include all the keys of E. However, I also need to specify a separate type for each field. Therefore, usi ...

How to conceal parameters in Angular URL?

Within the modeling-agency component, there is a button that routes to editModelingAgency/{{element.userid}}. Currently, clicking on this button takes the user to a specific route with a link like /base/editModelingAgency/15, but I want to show the link as ...

The Vue instance seems to be unable to recognize the shims-vue.d.ts file

I encountered an issue with my Vue file. Here is the code snippet: import Vue from 'vue'; import VueRouter from 'vue-router'; export default Vue.extend({ name: 'MyComponentsName', methods: { doRedirect() { this. ...

How to efficiently manage multiple namespaces in Angular with the help of socket.io

I have a scenario where I am working with two clients and have defined static namespaces "/CGI_ONE" and "/CGI_TWO". However, when I connect to "/CGI_TWO", it disconnects the previous socket.io connection. How can I manage both connections in node.js and an ...

The div element is finally loading properly after multiple clicks

I need some assistance with loading dynamic divs in Angular. I have created a button that adds new divs each time it is clicked in a specific area. However, once these new divs are added, they appear incorrectly: https://i.sstatic.net/sAE6q.png After add ...

The module "angular2-multiselect-dropdown" is experiencing a metadata version mismatch error

Recently, I updated the node module angular2-multiselect-dropdown from version v3.2.1 to v4.0.0. However, when running the angular build command, I encountered an "ERROR in Metadata version mismatch for module". Just to provide some context, I am using yar ...

Step-by-step guide on developing an AngularJs provider using TypeScript

As I've developed a Directive that incorporates various Css classes, it would greatly enhance its flexibility if the Css classes could be configured at Application start within the config section. I believe utilizing a provider is the appropriate appr ...

Why isn't my Bootstrap affecting Angular?

Hello, I am currently working on a project using Angular. Recently, I installed Bootstrap and added it to angular.json, but unfortunately, the changes did not take effect even after restarting the app. Here is the code snippet that I am currently using: h ...

Using the Async feature, I can retrieve the value of a string type when the return type of a function is Promise<any>

While working on a custom pipe, I encountered a situation that puzzled me. Can you explain why the code snippet below is considered valid? async transform(value: any): Promise<string> { let fullNameBasedOnPreference: string; fullNameBasedOnP ...