Ensure the information remains secure within the Ionic provider

In my Ionic 3 project, I am sending an API request and displaying the response on a page called Home.ts by using a Provider. I want to ensure that the data remains in the provider after the initial request so that all pages utilizing this Provider can access the same information without needing to make another API call. What would be the most effective approach to achieve this?

Versions: ionic CLI: 3.10; Ionic Framework: 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());
  }
}

Home.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>

Answer №1

Method 1:

To easily handle storage, consider using the storage module.

The storage module provides a simple way to store key/value pairs and JSON objects, utilizing various storage engines depending on the platform.

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

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

Method 2:

If you need to set an expiration for your value, consider utilizing the Ionic cache service.

For more information about the Ionic cache service, check out this article.

Answer №2

Simply implement the following code:

.cache(1)
.retain();

When working with your HTTP request observable, this method will store and retrieve the latest value. Retain ensures that the observable remains active as long as there are still observers.

Answer №3

To preserve the outcome, you have the option to save it within a class attribute belonging to the provider. The longevity of the provider is contingent upon its source: transfer it from the providers section of a particular page over to the providers segment within your application module. By doing so, the provider will remain active for as long as the application remains operational.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Flipping the Observable List in Angularfire2

Currently, I have implemented the following code to reverse the list: this.items = this.db.list('/privacy').map( (array) => {return array.reverse()} ) as FirebaseListObservable<any[]>; When displaying the list, I call it like this: &l ...

Issue detected in Angular 2 Heroes Tutorial: The element with the selector "my-app" was not found in the document

Currently, I am in the process of following along with the Heroes tutorial on the official angular website. The project was created using CLI and everything seemed to be working smoothly up until Part 6 on Routing: https://angular.io/tutorial/toh-pt5 In ...

Implementing data waiting strategy in Vue component using TypeScript for rendering

When working with the first component, I encountered a scenario where I needed to open a new page using the router functionality: In Component_1.vue: let route = this.$router.resolve({ name: 'Schedule', params : { id: (this.schedule[0].schedule ...

Validating Inputs with an Array of Values in my Angular 2 Application

I have been exploring ways to retrieve data from an array of values instead of a single value when using [(ngModel)] binding in my Angular 2 application. The current setup functions perfectly with a single value, as shown below. The data is pulled from the ...

Top-notch approach for consolidating Typescript Declaration files into a single comprehensive file

Is there any efficient way to package declaration files together without using the module declaration approach? declare module "path/to/file" { ... } declare module "path/to/file/sub/file" { ... } and so on. I have encountere ...

What is the best way to restrict the key of an object type to only be within a specific union in TypeScript?

I need to create a set of server types in a union like this: type Union = 'A' | 'B' | 'C'; After that, I want to define an object type where the keys are limited to only certain options from this Union: // Use only 'A&ap ...

Angular Image Cropping: A How-To Guide

I have been on the lookout for an Angular plugin that allows me to crop images before uploading them to the database. Despite spending all day searching, I have not been able to find a suitable plugin that meets my requirements. What I need specifically i ...

Is there a way to utilize "npm install ts-node-dev -D" in Termux?

npm ERR! code EACCES npm ERR! syscall symlink npm ERR! path ../acorn/bin/acorn npm ERR! dest /storage/emulated/0/bot-baiano/node_modules/.bin/acorn npm ERR! errno -13 npm ERR! Error: EACCES: permission denied, unable to create symlink fro ...

WebdriverIO encounters difficulty in clicking on an (Ionic) tab

I'm currently using WebdriverIO to perform some basic functionality tests on an Ionic (+ Angular) application. The setup of the framework seems to be working fine, but I am encountering difficulties when attempting to execute a click action on specifi ...

Tips for applying unique scss classes to a div based on a specific condition

Currently, I am developing a chat application where I want to showcase messages from one specific user on the right side of the screen while displaying messages from other users on the left side. <ion-item *ngFor="let message of messages | slice:0: ...

What method can I utilize to display a value that deviates from the one stored in the backend using Record?

Here is the HTML snippet that I am working with: <drop-down-list [name]="MeetingTool.Type" [options]="options$" [isRequired]="false" class="input-width" ...

server running on node encountered an error due to a port that is already in use

The Server instance emitted an 'error' event at: at emitErrorNT (net.js:1340:8) at processTicksAndRejections (internal/process/task_queues.js:84:21) { code: 'EADDRINUSE', errno: 'EADDRINUSE', syscall: 'listen', addre ...

How do I inform Jest that spaces should be recognized as spaces?

Here is some code snippet for you to ponder: import { getLocale } from './locale'; export const euro = (priceData: number): string => { const priceFormatter = new Intl.NumberFormat(getLocale(), { style: 'currency', currenc ...

Can you explain the distinction between needing ts-node and ts-node/register?

Currently, I am conducting end-to-end tests for an Angular application using Protractor and TypeScript. As I was setting up the environment, I came across the requirement to include: require("ts-node/register") Given my limited experience with Node.js, I ...

How to customize toggle icon in Angular Material mat-slide-toggle

I'm currently using Angular6 to design my user interface. The default style of the mat-slide-toggle button is shown below: https://i.stack.imgur.com/tIqus.png However, I would like the toggle button to have the appearance of the material-icons togg ...

What are some tips for keeping design proportions consistent on mobile apps?

Hey there, I have a question that may seem basic to some, but as a newbie in coding, I appreciate your patience. I've been working on an Ionic app and I'm struggling with maintaining CSS proportions of HTML elements. For instance, here's th ...

Exploring the versatility of Angular by creating various flex layouts with Angular Material cards

I'm struggling to implement the design shown below using cards and a flex layout in a responsive way. I've tried working on it using StackBlitz but haven't been able to get it right - the margin and layout get messed up on different screens. ...

What is causing the error 'router-outlet' to be unrecognized in Angular version 17?

I have recently set up a new angular project using Angular 17: If 'router-outlet' is considered an Angular component, double check that it is part of this module. If 'router-outlet' is recognized as a Web Component, make sure to inclu ...

Adjust the component's input value using a different component

Let's talk about two components in this scenario - HomeComponent and UserComponent. The UserComponent is a child of the HomeComponent and has the following structure: UserComponent.html: <form [formGroup]="form"> <div style="display:block ...

What is the best way to assign three different dates in my protractor test?

I am facing an issue with setting random dates in 3 date fields in a row using Protractor. The problem is that Protractor sets the dates too quickly and sometimes assigns invalid dates like: first data: 01/08/1990 (correct) second data: 01/09/0009 (inva ...