使用 *ngFor 遍历从服务器获取的数据

Using *ngFor to loop over data fetched from server

我对 Angular 很陌生。

我正在使用以下代码获取服务器上的帖子列表:

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

PostService.fetchPosts returns 然后我填充到 allPosts 变量中的响应。

然而,在视图中:

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

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

我的列表没有更新。

home.component.ts 文件:

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

您无法访问组件 HTML 文件中的静态字段。使用 allPosts 字段删除静态修饰符,并将 HomeComponent.allPosts 替换为 this.allPosts in home.component.ts file