更新时间:2023-01-28 10:42:04
我假设您有ngFor
可以像这样以articles-list.component.html
角显示文章
I am assuming that you have ngFor
to display your articles in your angular articles-list.component.html
like this
<div class="article" *ngFor="let card of cards" (click)="goToArticle(card )">
// your card html here
</div>
现在您有2个选择.
选项1
一种方法是在服务变量中的单击集中设置一个service
对象,然后在data.service.ts
One is to make a service
in set clicked article object in service variable and then get that article object
on your another page like this in your data.service.ts
clickedArticle : Object = {};
setCLickedArticleObj(obj){
clickedArticle = obj;
}
getClickedArticle(){
return clickedArticle;
}
在您的ariticles-list.component.ts
具有这样的功能
goToArticle(article){
this._dataService.setCLickedArticleObj(article)
this.router.navigate('/article-details')
}
在新的page/component
上,您可以像这样获得点击的物品
On your new page/component
you can get that clicked article object like this
// service import
import {DataService} from 'your-path-to-service'
constructor(private _dataService : DataService){
}
incomingArticleObject : Object = {};
ngOnInit(){
this.incomingArticleObject = this._dataService.getClickedArticle()
}
选项2
我假设您正在从back-end
api接收每篇文章_id
,因此您可以将点击的文章的_id
设置为localstorage
,在新的page/component
上,您可以将该点击点击article detail
api,了解有关新组件加载的文章详细信息.
对于此解决方案,您可以像这样在服务中创建功能
in option 2 i am assuming that you are receiving each article _id
form the back-end
api so you can set your clicked article's _id
to localstorage
and on your new page/component
you can get that clicked article details on new component load by hitting article detail
api.
For this solution you can make a function in your service like this
setClickedArticle(id){
localStorage.setItem('__ai', id)
}
getClickedAritcleId(){
return localStorage.getItem('__ai');
}
然后在您的articles-list.component.html
中,您将像这样
Then in your articles-list.component.html
you will have like this
<div class="article" *ngFor="let card of cards">
// your card html here
</div>
在您的articles-list.component.ts
中,您将具有这样的功能
In your articles-list.component.ts
you will have a function like this
articledId : String = '';
goToArticleDetails(id){
this._dataService.setClickedArticle(id);
this.router.navigate('/article-details');
}
在新的page/component
article-details.compnent.ts
上,您可以像这样在ngOnInit
上获取该文章的详细信息
And on your new page/component
article-details.compnent.ts
you can get that article detail on ngOnInit
like this
articleId : String = '';
articleDetails : Object = {};
ngOnInit(){
this.articleId = this._dataService.getClickedAritcleId()
this._dataService.getArticleById(this.articleId).subscribe(article=>{
this.articleDetails = article;
})
}