keepwalking
keepwalking

Reputation: 2654

Cache custom component content in ionic 2

I am creating a custom component which loads the innerHTML from a remote source. My question is how can i load the content when app loads. Right now, the content loads when the page shows and its a small delay until the text appears. Is there an event i can attach to that component to load the content when the app loads?

This is how my component looks like:

import {Component} from 'angular2/core'
import {DataProvider} from '../../providers/DataProvider'

@Component({

    'selector': 'ck-tos',
    templateUrl: 'build/directives/ckTos/ckTos.html',
    providers: [[Cashklick]],
})

export class ckTos {

    content: String = "";

    constructor(private DataProvider: DataProvider) {

        DataProvider.load('pages', 'terms').subscribe(
            data => {

                let response = data.json();
                if (response.content)
                    this.content = response.content;
                else if (response.error)
                    this.content = response.error;
                else
                    this.content = "Error: Unable to get any data ...";

            },
            err => {this.content = "Error: Unable to get any data ...";},
            () => console.log('DataProvider service for page terms completed')
        );
    }

}

When i open the app, i want this component to have content variable loaded and used without calling the remote service each time the component is rendered.

Upvotes: 1

Views: 1660

Answers (2)

Thierry Templier
Thierry Templier

Reputation: 202176

You could implement the following mechanism into your service:

export class DataProvider {
  constructor(private http:Http) {
  }

  load() {
    if (this.data) {
      return Observable.of(this.data);
    } else {
      return this.http.get(...)
                 .map(...)
                 .do(data => {
                   this.data = data;
                 });
  }
}

You need to share your service for the whole application:

bootstrap(AppComponent, [ DataProvider ]);

Be careful not to specify DataProvider within the providers attribute of your components.

Upvotes: 1

Günter Zöchbauer
Günter Zöchbauer

Reputation: 657338

You can either implement canReuse() https://angular.io/docs/ts/latest/api/router/CanReuse-interface.html so the component instance isn't recreated when navigating away from and back to the same component

or you you can move that code to a service (probably into DataProvider or another service that depends no DataProvider) and inject that service instead. The service instance will be kept alive by DI including the data.

Upvotes: 1

Related Questions