如何在angular9应用程序中保存加载后的数据以备将来使用



我有一个angular应用程序,其中categories加载在home页面上。所以我在ngOnInit上调用getCategories()函数,所以每当home页面加载时,所有类别都会从数据库中提取并显示在home页面上。这很好用。但这里的问题是,当我通过单击home页面中的category名称转到任何categories特定页面时,它会导航到该类别页面。但当我再次回到主页时,它再次从数据库中获取所有类别并在主页上呈现。所以最后的问题是,如果用户加载一次主页,在加载一次之后,它会访问主页多少时间,所以应用程序每次都会发出那个数量的http请求。所以我的问题是,有什么技术或方法可以摆脱这种多次重复的http Get调用吗?比如,如果用户加载home页面一次,那么我们会以某种方式将数据保存在任何位置,然后当用户再次从任何位置返回主页时,它会从我们的local scope而不是从数据库中获取数据吗?

由于导航离开时Components将被销毁,因此必须以更全局的方式保存数据。根目录中提供的CCD_ 16是Angular中的方法。这可能看起来像这样:

@Injectable({providedIn: 'root'})
export class MyRequestService {
private myRequest?:Observable<MyResponseType>;

constructor(private httpClient:HttpClient) {}
// Call this method whenever you want to access the "cached" request
public doRequest():Observable<MyResponseType> {
// only create a new request if you don't already have one stored
if (!this.myRequest) {
// save your request
this.myRequest = this.httpClient.get('http://someurl.de').pipe(
// Share the result - else every .subscribe will create another request, which you don't want
shareReplay(1)
)
}
// return the saved request
return this.myRequest;
}
}

在您的组件中,只需调用此方法,而不是在那里执行请求。

@Component({ /*...*/ })
export class MyComponent implements OnInit {
public myData?:MyResponseType;
constructor(private myRequestService:MyRequestService) {}
public ngOnInit():void {
// Use your service to make the request - obviously, you can alternatively store the
// observable instead of subscribing here and use the 'async' pipe on your template instead
this.myRequestService.doRequest()
.subscribe(myData => this.myData = myData);
}
}

相关内容

最新更新