我需要使用Angular2 +实现仅前端(最好是)应用程序,并且所需的功能之一是,用户必须能够在网站的本地存储(例如cookie)中保存其喜爱的项目列表。 。问题在于他们还必须能够共享此列表的链接。我是Web开发人员的新手,所以我不知道如何实现这种功能。
我在项目中使用Angular 2。这是一个非常简单的网站,没有用户帐户/登录名,只是从第三方API提取的数据,然后向用户显示项目,他们可以将其中一些标记为收藏。
答案 0 :(得分:2)
我看到的唯一方法是使用数组作为queryparam生成指向您网站端点的链接(用','分割数组,即:'item1,item2,...) 在此数组中,您将放入收藏夹项目列表。
然后在此端点中,收集queryparam并显示收藏夹项目列表:
itemIds: string[]
constructor(private activatedRoute: ActivatedRoute, private router: Router) {}
ngOnInit(): void {
this.routerSubscription = this.router.events.subscribe(
(routerEvent: RouterEvent) => {
if (routerEvent instanceof NavigationEnd) {
this.itemIds= this.activatedRoute.snapshot.queryParamMap.get('itemIds').split(',');
}
}
);
}
答案 1 :(得分:1)
如果您希望网页能够使用没有任何后端的url共享状态,则可以在查询参数中传递 state 。
在您的情况下,由于需要项目列表,因此需要传递id
的列表,您可以使用该列表从第三方API提取项目并重建相同的页面数据。
在页面加载时检查查询参数,并创建具有相应查询参数的页面链接。
import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute, Params } from '@angular/router';
@Component({
selector: 'kb-example-page',
templateUrl: './example-page.component.html',
styleUrls: ['./example-page.component.scss']
})
export class ExamplePage implements OnInit {
constructor(private router: Router,
private activeRoute: ActivatedRoute,
private examplePageService: ExamplePageService) {}
ngOnInit() {
const queryParams = this.activeRoute.snapshot.queryParams;
// get the list of items
// if queryParam exists, returns an array
// if not, parsedItems will be undefined
const parsedItemIds = queryParams &&
queryParams.items &&
queryParams.items.split(',');
if (parsedItemIds) {
this.fetchData(parsedItemIds);
}
}
createShareableLink(items: any[]) {
// create a list of item ids in a queryParam syntax
const itemsQueryParam = 'items=' + items.map((item) => item.id).join(',');
// create a link to this page with the
// queryParams representing the items
return `${ SITE_URL }?${ itemsQueryParam }`;
}
fetchData(itemIds: string[]) {
this.examplePageService
.fetchItems(items)
.subscribe(() => /* initialize the page with the data */);
}
}
如果要确保URl不大,可以使用this one之类的URL缩短服务。
这将创建一个链接到起酥油服务站点的链接,该链接将重定向到包含url中所有查询参数的站点