Leveraging *ngFor to iterate through data retrieved from the server

I am completely new to Angular.

Currently, I am retrieving the list of posts from the server using the code snippet below:

loadPosts():boolean{
if (!LoginService.authenticated){
  console.log('not auth');
  return false;
}
// fetching posts.
console.log('load');
PostService.fetchPosts(
  (response: Response) => {
    HomeComponent.allPosts = response;
    console.log("POSTS");
    console.log(HomeComponent.allPosts);
});

The PostService.fetchPosts function provides a response that is then stored in the allPosts variable.

However, when it comes to displaying these posts in the view:

<div *ngIf="!authenticated(); else elseBlock">
 Please log in first.
</div>

<ng-template #elseBlock>
    <div *ngFor="let post of allPosts">
      {{ post.heading }}
    </div>
</ng-template>

I noticed that my list of posts is not being refreshed or updated as expected.

In the home.component.ts file:

export class HomeComponent implements OnInit {

  static allPosts;

  constructor(private ref: ChangeDetectorRef, private loginService: LoginService, private http: HttpClient, private postService: PostService) {
    this.loginService.authenticate(undefined, undefined, undefined);
    // setInterval(() => { console.log('checking'); this.ref.detectChanges}, 500 );
  }

  ngOnInit() {
    this.loginService.authenticate(undefined, this.loadPosts, undefined);
  }

  authenticated(){
    return LoginService.authenticated;
  }

  add(){
    HomeComponent.allPosts = [{heading:'okay'}];
  }

  loadPosts():boolean{
    if (!LoginService.authenticated){
      console.log('not auth');
      return false;
    }
    // fetching posts.
    console.log('load');
    PostService.fetchPosts(
      (response: Response) => {
        HomeComponent.allPosts = response.json();
        console.log("POSTS");
        console.log(HomeComponent.allPosts);
    });
  }
}

Regarding the post.service.ts file:

export class PostService {

  static getPostUrl = 'http://localhost:8009/user/getposts';
  static http;

  constructor(private http: HttpClient) { PostService.http = http }

  static fetchPosts(successCallback, errorCallback?){
    this.http.get(this.getPostUrl, { withCredentials: true }).subscribe(
      (response: Response) => {
        successCallback(response);
      },
      (error) => {
        console.log(error);
        errorCallback? errorCallback(error) : {};
      }
    );
  }
}

Answer №1

In the HTML file of a component, it is not possible to access static fields. To resolve this issue, remove the static modifier from the allPosts field and replace HomeComponent.allPosts with this.allPosts in the home.component.ts file.

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

Fixing the forwardRef issue with react-router-dom and material-ui

Despite implementing the forwardRef as recommended in various posts and Material-UI website examples, I am still encountering a warning in the console that has me puzzled. I am working on setting up a drawer with a list of items that are React Router link ...

Is there a way to retrieve the latitude and longitude values using a plugin and then make a web service call in Ionic with Angular 5?

I am currently trying to retrieve the latitude and longitude coordinates of a location by using geocode in Angular 5 within the Ionic framework. Once I have obtained the lat long, I intend to pass it to my service. The issue I am facing is that my service ...

Importing components in real-time to generate static sites

My website has a dynamic page structure with each page having its unique content using various components. During the build process, I am statically pre-rendering the pages using Next.js' static site generation. To manage component population, I have ...

Angular - The element contains an implicit 'any' type due to the absence of an index signature in the 'AbstractControl' type

Within my Angular-11 project, I am utilizing the following TypeScript code: multistep = new FormGroup({ userDetails: new FormGroup({ first_name: new FormControl(''), last_name: new FormControl(''), other_na ...

Exploring the process of implementing inheritance in TypeScript from a JavaScript class

I am using a JavaScript module to extend a Class for a Custom extended Class. I have written my Custom Class in TypeScript, but I encountered the following error messages: Property 'jsFunc' does not exist on type 'tsClass'.ts(2339) I ...

Tips for printing pages in a combination of portrait and landscape modes

Currently, I am working on an angular component that handles UI rendering and printing. In this particular project, I need the initial 2 pages to be displayed in landscape mode, followed by one page in portrait mode after a page break. I have attempted to ...

Best practice for entering events in callback

Recently, I delved into Angular because I anticipate needing to use it down the line. My current focus is on studying components communication, particularly from child to parent. I came across various methods of achieving this. In each example, the ChildC ...

Perform an Angular HTTP request and await responses from multiple sources

I'm currently working with Angular 11 and looking to make an HTTP call to an API that will trigger a server-side process. Here's the code for the HTTP call: processData(data) { return this.httpClient.post('https://myurl/api/process&apos ...

What are the counterparts of HasValue and .Value in TypeScript?

There is a method in my code: public cancelOperation(OperationId: string): Promise<void> { // some calls } I retrieve OperationId from another function: let operationId = GetOperationId() {} which returns a nullable OperationId, operat ...

In TypeScript, use a key index signature for any properties that are not explicitly defined

In various instances, I have encountered scenarios where it would have been beneficial to implement the following (in a highly abstracted manner): export interface FilterItem { [key: string]: string | undefined; stringArray?: string[]; } However, thi ...

Upgrade to Angular 12: TypeScript is now an essential requirement for the Angular Compiler

Recently, I made sure to update my project to the latest Angular version. After running "ng update", I received a confirmation that everything was already up to date, indicating that all required packages had been successfully updated in the last step of t ...

The live updates for user data in Firestore are not being reflected immediately when using valueChanges

Utilizing Angular and Cloud Firestore for my backend, I have a setup where users can follow or unfollow each other. The issue arises when the button text and list of followers/following do not immediately update on the front end after a successful click ev ...

Using Angular to pass an index to a pipe function

Currently, I am attempting to incorporate the *ngFor index into my pipe in the following manner: <td *ngFor="let course of courses | matchesTime:time | matchesWeekday:i ; index as i">{{course.courseName}}</td> This is how my pipe is structure ...

Placing the Y-axis title beside the initial marker in Highcharts: A guide

I am currently working on an application using Angular and am relatively new to Highcharts. I have a specific requirement where the title should be placed next to the first marker of a bar chart, with dynamically changing values. Here is the code snippet I ...

When creating a form group within another form group, ensure that formGroup is passed a FormGroup instance

I have created a form for adding users, which includes fields to input their birthdate. this.userFG = this.formBuilder.group({ name: [""], family: [""], birthDate: this.formBuilder.group({ day: [""], month: [""], year: [""] }) }); Wh ...

Tips for developing a web-based whiteboard application

I am tasked with developing a web application that allows users to design factory layouts by dragging and dropping pre-built components like robots, manufacturing cells, and conveyors onto a canvas. The goal is to create something similar to websites such ...

Is it possible to assign a property value to an object based on the type of another property?

In this illustrative example: enum Methods { X = 'X', Y = 'Y' } type MethodProperties = { [Methods.X]: { x: string } [Methods.Y]: { y: string } } type Approach = { [method in keyof Method ...

What is the best way to sift through an array containing arrays of arrays that hold objects?

My attempt to filter an array of arrays of objects is not working as expected. constructNewGrid(filterText){ if(searchText == ""){ this.constructedGrid = this.fullGrid; return; } this.constructedGrid = []; this.c ...

Struggling to utilize a custom react-three-fiber component despite specifying the custom type within the react-three-fiber module

Currently developing a react application focused on visualizing mathematical concepts with the help of react-three-fiber. Utilizing TypeScript, I discovered that by extending custom ThreeElements (https://docs.pmnd.rs/react-three-fiber/tutorials/typescript ...

The TSOA Express application is experiencing difficulties in retrieving endpoints

Currently, I am working on developing a REST API using node.js and Typescript. To aid in the documentation process, I am utilizing tsoa and swagger. The build process is successful, and the swagger.json file is generated without any issues. However, when a ...