angulartypescriptngfordynamic-list

Using *ngFor to loop over data fetched from server


I am very new to Angular.

I am fetching the list of posts on the server using the following code:

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

The PostService.fetchPosts returns the response which I then populate into the allPosts variable.

However, 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>

My list is not being updated.

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;
    }
    // fetch posts.
    console.log('load');
    PostService.fetchPosts(
      (response: Response) => {
        HomeComponent.allPosts = response.json();
        console.log("POSTS");
        console.log(HomeComponent.allPosts);
    });
  }
}

post.service.ts:

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

Solution

  • You cannot access static field in the component's HTML file. Remove static modifier with allPosts field and replace HomeComponent.allPosts with this.allPosts in home.component.ts file