如何使用 Angular 从 REST API 读取 JSON 响应
How to read JSON response from a REST API using Angular
我正在学习 Angular 基础知识。我选择了一个非常小的项目。我正在使用 JSONPlaceholder,假的 REST API。我想读取所有 post 并使用简单的 ngFor
循环将它们呈现在页面上。我为此创建了一项服务。我会一一展示我的代码。但这里的 stackblitz 是一样的。
我只需要这些文件的帮助:
- post-列表
- post界面
- post.service
在阅读文章并观看 pluralsight 和 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这样会节省大家的时间和精力。我的问题是:
Can't bind to 'ngForOf' since it isn't a known property of 'div'. ("
Error: 0.9.1/dist/zone.j
请指出错误并指正。
首先你应该改变你的服务并在 HttpClientModule
.
中使用 HttpClient
export class PostService {
constructor(private httpClient: HttpClient) {};
getAllPosts(): Observable<Post[]> {
return this.httpClient.get<Post[]>('https://jsonplaceholder.typicode.com/posts');
}
}
还要注意正确导入 HttpClientModule
,并且 CommonModule
您正在使用子模块。如果不导入,则无法访问 async
等常用指令。
@NgModule({
imports:[
CommonModule,
HttpClientModule,
...
然后你有多个选项来检索和呈现你的结果,这里有两个主要的选择:
选项 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>
请参阅 updated stackblitz demo 以了解使用 Observable
和 async
管道的推荐选项。
我正在学习 Angular 基础知识。我选择了一个非常小的项目。我正在使用 JSONPlaceholder,假的 REST API。我想读取所有 post 并使用简单的 ngFor
循环将它们呈现在页面上。我为此创建了一项服务。我会一一展示我的代码。但这里的 stackblitz 是一样的。
我只需要这些文件的帮助:
- post-列表
- post界面
- post.service
在阅读文章并观看 pluralsight 和 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这样会节省大家的时间和精力。我的问题是:
Can't bind to 'ngForOf' since it isn't a known property of 'div'. ("
Error: 0.9.1/dist/zone.j
请指出错误并指正。
首先你应该改变你的服务并在 HttpClientModule
.
HttpClient
export class PostService {
constructor(private httpClient: HttpClient) {};
getAllPosts(): Observable<Post[]> {
return this.httpClient.get<Post[]>('https://jsonplaceholder.typicode.com/posts');
}
}
还要注意正确导入 HttpClientModule
,并且 CommonModule
您正在使用子模块。如果不导入,则无法访问 async
等常用指令。
@NgModule({
imports:[
CommonModule,
HttpClientModule,
...
然后你有多个选项来检索和呈现你的结果,这里有两个主要的选择:
选项 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>
请参阅 updated stackblitz demo 以了解使用 Observable
和 async
管道的推荐选项。