Angular单页应用在每次进入新路由时都从服务器获取数据。
创始人
2024-10-23 20:30:41
0

可以通过使用Angular的Resolve守卫来缓存数据,以便在每次访问某个路由时不需要从服务器中再次获取相同的数据。以下是一个示例:

// defining routes in app.module.ts const appRoutes: Routes = [ { path: '', component: HomeComponent, resolve: { data: HomeResolver } }, { path: 'products', component: ProductsComponent, resolve: { data: ProductResolver } } ];

// resolver for home component @Injectable() export class HomeResolver implements Resolve { constructor(private dataService: DataService) {}

resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) { return this.dataService.getHomeData(); } }

// resolver for products component @Injectable() export class ProductResolver implements Resolve { constructor(private dataService: DataService) {}

resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) { return this.dataService.getProducts(); } }

// data service to fetch data from server @Injectable() export class DataService { private homeData: any; private productsData: any;

constructor(private http: HttpClient) {}

getHomeData() { if (this.homeData) { return of(this.homeData); } else { return this.http.get('api/home').pipe( tap(data => this.homeData = data) ); } }

getProducts() { if (this.productsData) { return of(this.productsData); } else { return this.http.get('api/products').pipe( tap(data => this.productsData = data) ); } } }

在上面的代码中,我们定义了两个路由和两个Resolve守卫,分别为HomeComponent和ProductsComponent。在每个守卫中,我们使用一个DataService来获取数据。为了避免在每个路由进入时都从服务器获取相同的数据,我们可以使用DataService中的缓存机制,每个数据仅需要从服务器获取一次,并在之后的路由中重复使用

相关内容

热门资讯

目前来看!hhpoker透视工... 目前来看!hhpoker透视工具,如何下载德普之星辅助软件,都是是有挂(竟然有挂)如何下载德普之星辅...
推荐一款!pokeplus脚本... 推荐一款!pokeplus脚本,hhpoker外挂靠谱吗,总是是真的有挂(有挂教程)1、脚本辅助下载...
随着!德普之星辅助器怎么用,德... 随着!德普之星辅助器怎么用,德扑之星辅助工具如何设置,一贯是有挂(真实有挂)1、下载好德扑之星辅助工...
热点推荐!wepoker透视破... 热点推荐!wepoker透视破解版,werplan脚本,真是是有挂(真的有挂)1、有没有辅助教程、有...
无独有偶!wepoker软件安... 无独有偶!wepoker软件安装包,德扑之星透视免费,原来是有挂(确实有挂)在进入德扑之星透视免费软...
重大科普!wepoker俱乐部... 重大科普!wepoker俱乐部辅助器,约局吧透视挂下载,一贯存在有挂(有挂总结)小薇(辅助器软件下载...
无独有偶!hhpkoer辅助器... 无独有偶!hhpkoer辅助器,德普之星私人局辅助器,切实是真的有挂(有挂工具)1、许多玩家不知道德...
玩家交流!hhpoker是真的... 玩家交流!hhpoker是真的吗,如何下载wpk透视版,好像真的是有挂(新版有挂)运辅助工具,进入游...
第三方辅助挂!pokemomo... 第三方辅助挂!pokemomo辅助工具,德普之星透视软件免费入口官网,都是真的有挂(有挂详情)1、德...
盘点一款!wejoker辅助器... 盘点一款!wejoker辅助器怎么卖,pokemmo辅助器脚本下载,好像真的是有挂(有挂方针)脚本下...