[英]Cache custom component content in ionic 2
I am creating a custom component which loads the innerHTML from a remote source. 我正在创建一个自定义组件,该组件将从远程源加载innerHTML。 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. 当我打开应用程序时,我希望此组件具有加载和使用的内容变量,而无需在每次呈现该组件时调用远程服务。
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. 注意不要在组件的
providers
属性内指定DataProvider
。
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 您可以实现
canReuse()
https://angular.io/docs/ts/latest/api/router/CanReuse-interface.html,以便在从同一个组件导航和返回相同组件时不会重新创建组件实例
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. 或者,您可以将该代码移至服务(可能移至
DataProvider
或不依赖DataProvider
其他服务)中,然后注入该服务。 The service instance will be kept alive by DI including the data. 服务实例将由包含数据的DI保持活动状态。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.