如何从ID以角度显示JSON对象(7)
我正在尝试创建一个CRUD应用程序,它的工作方式有点像博客。我有所有的创建、读取、更新和删除功能。我只想显示一个对象的数据(示例:标题,说明),基于作为路由一部分的对象ID(localhost:4200/route/0) 我可以使用如何从ID以角度显示JSON对象(7),json,typescript,angular7,Json,Typescript,Angular7,我正在尝试创建一个CRUD应用程序,它的工作方式有点像博客。我有所有的创建、读取、更新和删除功能。我只想显示一个对象的数据(示例:标题,说明),基于作为路由一部分的对象ID(localhost:4200/route/0) 我可以使用获取数据以显示我想要的方式,但不能使用上的ngFor或任何其他标记 app-routing-module.ts {path:'article/:id',component:ArticleComponent} db.json "articleInfo": [
获取数据以显示我想要的方式,但不能使用
上的ngFor
或任何其他标记
app-routing-module.ts
{path:'article/:id',component:ArticleComponent}
db.json
"articleInfo": [
{
"id": 0,
"title": "Marinara Pasta",
"category": "Italian",
"author": "Sample",
"date": "06/11/2019",
"description": "A classic Italian dish. Quick, easy, and ready to eat in only 15 minutes.",
"image": "/assets/sample.png"
}
]
data.service.ts
baseUrl:string=”http://localhost:3000";
getData(id:number):可观察{
返回此.http.get(this.baseUrl+'/articleInfo/'+id)
}
第3.1.ts条
导出类ArticleComponent实现OnInit{
id=this.actRoute.snapshot.params['id'];
条款:任何=[];
构造函数(私有数据服务:数据服务,公共actRoute:ActivatedRoute,公共路由器:路由器){}
loadIdData(){
返回this.dataService.getData(this.id).subscribe(data=>{
本文件=数据;
})
}
恩戈尼尼特(){
这是loadIdData();
}
}
article.component.html
<div *ngFor="let info of articles">
<h2> {{info.title}} </h2>
<h6> {{info.description}}</h6>
</div>
{{info.title}
{{info.description}
我在ArticleComponent.ngfactory.js中获得错误和错误上下文。您可以将article.component.ts更新为:
export class ArticleComponent implements OnInit {
id;
articles: Observable<any[]>;
constructor(private dataService: DataService, public actRoute: ActivatedRoute, public router: Router) { }
ngOnInit() {
this.id = this.actRoute.snapshot.params['id']
this.loadIdData();
}
loadIdData() {
this.articles = this.dataService.getData(this.id);
}
}
导出类ArticleComponent实现OnInit{
身份证件
物品:可见
注意:|async
只是一些糖,并不是真正需要的。您可以保留代码,只需更新构造函数或ngOnInit
中id的值即可。
这里有一个找出了我的错误所在。ngFor
不是显示一组数据的正确方法。它需要多组数据,因此不会在页面上显示任何内容。对我有效的方法是从我的文章中提取信息:any=[];
{{articles.id}
{{articles.title}}
{{articles.description}}
要更好地解释为什么这样做,请参阅。您好,谢谢您的回复。不幸的是,这并没有解决我的问题。在我的原始代码中,我能够使用
显示正确的数据。您更新的代码没有显示任何与ngFor或ngModel相关的内容。问题可能是其他问题吗?
<div *ngFor="let info of articles | async">
<h2> {{info.title}} </h2>
<h6> {{info.description}}</h6>
</div>