如何使用Angular从REST API读取JSON响应

问题描述 投票:0回答:1

我正在学习Angular基础知识。我已经完成了一个非常小的项目。我正在使用JSONPlaceholder(伪造的REST API)。我想阅读所有帖子,并使用简单的ngFor循环将它们呈现在页面上。我已经为此创建了服务。我将一一展示我的代码。但这是相同的stackblitz。我只需要这些文件的帮助:

  1. 帖子列表
  2. 发布界面
  3. post.service

我阅读了散文并观看了涉及复数视力和youtube的教程后,从头开始编写了这么多代码,但是现在我被封锁了。这是我的代码:

post.ts

export interface Post {
  userId: number;
  id: number;
  title: string;
  body: string;
}

post.service.ts

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class PostService {

  constructor() {}

  getAllPosts():Observable<Post[]> {
    return fetch('https://jsonplaceholder.typicode.com/posts')
      .then(response => response.json())
      .then(json => console.log(json))
  }
}

post-list.component.ts

import { PostService } from './post.service';
import { Component } from '@angular/core';

import { Post } from './post'

@Component({
  templateUrl: './post-list.component.html',
})
export class PostList {

  posts: Post[] = [];
  errorMessage="";

  constructor(private postservice: PostService) {
    this.postservice.getAllPosts().subscribe({
      next: posts => {
        this.posts=posts;
      },
      error: err => this.errorMessage = err
    });
  }
}

[我坚持,请查看stackblitz,它将节省每个人的时间和精力。我的问题是:

无法绑定到'ngForOf',因为它不是'div'的已知属性。 (“

错误:0.9.1 / dist / zone.j

请指出我的错误并纠正我。

angular typescript observable angular-services
1个回答
0
投票

选项1

@Component({
  templateUrl: './post-list.component.html',
})
export class PostList {
  posts: Post[] = [];
  errorMessage: string;

  constructor(private postService: PostService) {}

  ngOnInit() {
    this.posts = this.postService.getAllPosts().subscribe(
      posts => {
        this.posts = posts
      },
      error => {
        this.errorMessage = error;
      }
    );
  }
}

选项2(推荐)

@Component({
  templateUrl: './post-list.component.html',
})
export class PostList {
  posts$: Observable<Post[]>;
  errorMessage: string;

  constructor(private postService: PostService) {}

  ngOnInit() {
    this.posts$ = this.postService.getAllPosts().pipe(
      catchError(error => {
        this.errorMessage = error;
      });
    );
  }
}

template.html:

<div *ngFor="let post of posts$ | async">
  <p>{{ post.userId }}</p>
  ...
</div>
© www.soinside.com 2019 - 2024. All rights reserved.