我正在尝试创建一个有angular和firebase的“博客”。我在Angular和Firebase上的第一个项目做得很好。
我创建了加载所有条目的首页,然后添加了“阅读更多...”指向特定文章的路由的超链接加上条目的id。下面是HTML:
<div style="background-color:white" class=" contenedorBlog">
<h1 style="padding-top:100px;" class="text-center mb-4">Pizarrón</h1>
<div *ngFor="let item of items" style="padding:40px" class="rounded">
<h2> {{item.title}} </h2>
<p>Date: {{ item.systemDate }}</p>
<div class="content" [innerHTML]="item.content"></div>
<a [routerLink]="['/article', item.id]">Read more...</a>
</div>
</div>
下面是文章组件的HTML:
<div style="background-color:white" class=" contenedorBlog">
<div style="padding:40px" class="rounded">
<h2> {{items.title}} </h2>
<p>Fecha: {{ items.systemDate }}</p>
<div class="content" [innerHTML]="items.content"></div>
</div>
</div>
我正在尝试弄清楚如何调用路由上具有该id的特定对象(article/:id)。
这就是我目前所拥有的(article.component.ts)
export class ArticlesComponent implements OnInit {
items:any;
constructor(private blogService: UploadService, private route: ActivatedRoute) {
this.route.params.subscribe(params=> {
this.items=this.blogService.getObjectById(params['id']);
});
}
ngOnInit() {
}
}
问题是。我不知道下一步该怎么办。我在一个服务中调用了一个函数,我只想检索包含路由上id的对象。
getObjectById(id) {
///Help
}
非常感谢并为我不太好的英语感到抱歉。
发布于 2018-06-01 12:26:44
更改:
this.items=this.blogService.getObjectById(params['id']);
至:
this.blogService.getObjectById(params['id']).subscribe( i => {
this.items = i;
})
它们在getObjectById(id)中:
getObjectById(id) {
return this.afs.collection('collectionName').doc(id).valueChanges()
}
如果只想要一次该值,请在".subscribe“之前使用".take(1)”
如果不想看到“*ngIf=”错误,还需要将"items“放在显示”items“的元素中。
发布于 2018-06-01 09:30:07
在构造函数上定义一个AngularFirestore变量,然后在函数中使用它,如下所示:
constructor(private afs: AngularFirestore){
this.route.params.subscribe(params=> {
this.getObjectById(params['id']);
});
}
getObjectById(id) {
return this.afs.collection('collection_name')
.doc(id)
.ref;
}
然后,您可以在组件上使用函数,如下所示:
this.blogService.getObjectById(params['id']).get().then(res => {
console.log(res)
})
https://stackoverflow.com/questions/50634477
复制相似问题