我通过从JSON API获取数据来创建新闻应用程序,我只想将我的数据存储在Ionic的存储中,并在用户不再具有互联网连接时显示存储内容 .
目前,我使用HttpClient检索我的数据并返回一个Observable .
我可以将它们存储在存储器中并显示它 . 但是我不确定我的生命周期是否正常工作,我不知道我做的是不是很好 .
文章服务:
import {Injectable} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import 'rxjs/add/operator/map';
import {Platform} from "ionic-angular";
import {ArticleCard} from "../classes/ArticleCard";
import {Observable} from "rxjs/Observable";
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';
import {IArticleCard} from "../interfaces/IArticleCard";
@Injectable()
export class ArticlesService {
urlArticlesCards: string = "https://mylink";
constructor(private http: HttpClient, public platform: Platform) {
}
getAlaUneCards(): Observable<IArticleCard[]> {
return this.http.get<any>(this.urlArticlesCards)
.map(res => {
return res.map(article => {
return new ArticleCard(
article.id,
article.image,
article.titre,
);
});
});
}
}
界面:
export interface IArticleCard {
results: {
id: number;
image: string;
titre: string;
}[]
}
ArticleCard:
export class ArticleCard {
id: number;
image: string;
titre: string;
constructor(id: number, image: string, titre: string) {
this.id = id;
this.image = image;
this.titre = titre;
}
}
主页:
observable$: Observable<IArticleCard[]>;
tabCards: Array<Object>= [];
constructor(public navCtrl: NavController, private articleService: ArticlesService, private storage: Storage) {}
ionViewWillEnter() {
this.observable$ = this.articleService.getAlaUneCards();
this.observable$.subscribe(cards => {
if(cards){
this.storage.set('alaune_cards', cards);
}
this.storage.get('alaune_cards').then((card) => {
this.tabCards = card;
})
});
}
1 回答
我可以想到一些简单的改进:
1)您不需要重新获取刚刚存储在订阅方法中的内容 . 你可以在
if (cards) {
分支内设置this.tabCards = card;
.2)我只建议存储有限数量的数据,也许是最后50篇文章?过去的任何事情都可以从历史上从GET endpoints 中获取 .
3)如果你的目标是在列表中显示很多文章,我强烈建议实现无限滚动https://ionicframework.com/docs/api/components/infinite-scroll/InfiniteScroll/ . 看看你是否可以使你的urlArticlesCards GET endpoints 可分页 . 这将使您的应用整体表现更好 .