我有一个json数组,我从REST API调用中收集如下:
[
{"id":1,"title":"Title One","author":"Auth One"},
{"id":2,"title":"Title Two","author":"Auth Two"},
{"id":3,"title":"Another Title","author":"Another author"}
]
我创建了一个类posts.model.ts来表示帖子所包含的内容:
export class Post {
id: Number;
title: string;
author: string;
}
我的[[view-component.component.html(我很抱歉,我知道这个可怕的名字)看起来如下:
<p>
Post ID:<br>
<input type="text" [(ngModel)]="id">
</p>
<p>
<button (click)="search()">Search</button>
</p>
<div *ngIf="PostList">
<div *ngFor="let post of PostList">
Post ID: {{post.id}}<br>
Post Title: {{post.title}}<br>
Post Author: {{post.author}}
<hr>
</div>
</div>
和我的像这样view-component.component.ts
import { Component, OnInit, Input } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Post } from './post.model';
@Component({
selector: 'app-view-component',
templateUrl: './view-component.component.html',
styleUrls: ['./view-component.component.css']
})
export class ViewComponentComponent implements OnInit {
@Input('post') post: Post;
id: string = "";
PostList: any = [];
constructor(private http: HttpClient) { }
ngOnInit(): void { }
search() {
this.http.get('http://localhost:3000/posts/' + this.id)
.subscribe((data: {}) => {
this.PostList = data;
console.log("This is what I got back = " + JSON.stringify(data));
})
}
}
我观察到的是,当我单击输入字段中没有任何内容的按钮时(我希望所有帖子都被退回(这按预期工作,并且我获得了所有帖子的完整列表))。但是,例如,当我在输入字段中输入数字“ 2”并单击按钮时,我希望只看到显示的第二篇文章(“标题二”“认证二”,但是什么也不显示。
正如您在“ .ts”文件中看到的那样,我将在search()函数中返回的字符串写到控制台。当我搜索第二篇文章时,我得到以下内容:
This is what I got back = {"id":2,"title":"Title Two","author":"Auth Two"}
但是,html页面上什么也不显示。
object
。您需要从后端返回一个带有1个元素的array
:[{"id":2,"title":"Title Two","author":"Auth Two"}]
interface
而不是class
export interface Post {
id: Number;
title: string;
author: string;
}
PostList: Post[];
中使用创建的接口,并且我也将其保留为未定义状态,以便<div *ngIf='PostList'>
起作用,因为只有在未定义数组的情况下,检查才为false。this.http.get<Post[]>
时使用该接口,并在从API .subscribe((data: Post[]) =>
接收数据时再次使用该接口this.http.get<Post[]>('http://localhost:3000/posts/' + this.id)
.subscribe((data: Post[]) => {
this.PostList = data;
console.log("This is what I got back = " + JSON.stringify(data));
})
如果需要,请随时与我联系以获得进一步的帮助。