gpt4 book ai didi

angular - 将数据保存在 Ionic 提供程序中

转载 作者:搜寻专家 更新时间:2023-10-30 21:49:55 25 4
gpt4 key购买 nike

我正在使用 Ionic 3 发出 API 请求,并使用 Provider 在页面 Home.ts 上显示它。我需要在第一次请求后将数据保留在提供程序中,以便所有使用此提供程序的页面都可以访问相同的信息,而无需重新请求 API。执行此操作的最佳方法是什么?

版本:ionic CLI:3.10; ionic 框架:3.7.1


people-service.ts:

import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';

import 'rxjs/add/operator/do';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import { Observable } from 'rxjs/Observable';

@Injectable()
export class PeopleServiceProvider {
requisicao: any;
films: Observable<any>;
//getApiUrl : string = "https://jsonplaceholder.typicode.com/posts";
getApiUrl : string = "https://randomuser.me/api/?results=3";


constructor(public http: Http) {
this.requisicao = null;
}

// returns a Observable
getHTTP(docache: boolean) {
return this.http.get(this.getApiUrl)
.do(res => console.log(res.json()))
.map(res => res.json());
}
}

首页.ts:

import { Component } from '@angular/core';
import { NavController, LoadingController } from 'ionic-angular';
import {PeopleServiceProvider} from '../../providers/people-service/people-service';
import { Observable } from 'rxjs/Observable';


@Component({
selector: 'page-home',
templateUrl: 'home.html',
providers: [PeopleServiceProvider]
})
export class HomePage {

films: Observable<any>;
public people: any;
req: any;
constructor(public navCtrl: NavController, public loading: LoadingController, public peopleService: PeopleServiceProvider) {
this.people = null;
}

loadPeople(docache:boolean) {

let loader = this.loading.create({
content: 'Wait...',
});

loader.present().then(() => {
this.req = this.peopleService.getHTTP(docache);
this.req.subscribe((data)=>{
this.people = data.results;
console.log(this.people);
});
// this.peopleService.getPosts(docache);

loader.dismiss();

});

}
}

Home.html

  <button ion-button secondary (click)='loadPeople(true);'>Do cache</button>

最佳答案

方法一:

您可以轻松使用 storage module为此。

Storage is an easy way to store key/value pairs and JSON objects. Storage uses a variety of storage engines underneath, picking the best one available depending on the platform.

 // set a key/value
storage.set('name', 'myName');

// Or to get a key/value pair
storage.get('name').then((val) => {
console.log('Your name is', val);
});

方法二:

如果您需要在某个时候使该值过期,那么您可以使用 Ionic cache service

关于 it is here 的好文章.

关于angular - 将数据保存在 Ionic 提供程序中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46798471/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com