我有这段代码应该显示先前发送的通知。每次用户访问页面时都会出现更新的通知列表,他们也应该能够在dorefresh(下拉列表)上更新内容。
import { Component } from '@angular/core';
import { ToastController, Refresher } from 'ionic-angular';
import { OneSignalData } from '../../providers/onesignal-data';
import { NavController, NavParams } from 'ionic-angular';
@Component({
selector: 'page-notifications',
templateUrl: 'notifications.html',
})
export class NotificationsPage {
notifications: any = [];
constructor(
public navCtrl: NavController,
public navParams: NavParams,
public onesignalData: OneSignalData,
public toastCtrl: ToastController,
) {}
ionViewDidLoad() {
console.log('ionViewDidLoad NotificationsPage');
this.updateNotifications();
}
updateNotifications(){
this.onesignalData.getNotifications().subscribe((notifications) => {
this.notifications = notifications;
console.log(notifications)
});
}
doRefresh(refresher: Refresher) {
this.onesignalData.getNotifications().subscribe((notifications) => {
this.notifications = notifications;
console.log(notifications)
setTimeout(() => {
//this.updateNotifications();
refresher.complete();
const toast = this.toastCtrl.create({
message: 'Push Notifications have been updated.',
duration: 3000
});
toast.present();
}, 1000);
});
}
}
应该从另一个看起来像这样的文件中获取数据:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/observable/of';
@Injectable()
export class OneSignalData {
data: any;
constructor(
private http: HttpClient
) {}
load(): any {
if (this.data) {
return Observable.of(this.data);
} else {
return this.http.get('https://onesignal.com/api/v1/notifications?app_id=XXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXX&limit=50',
{ headers: { 'Authorization': 'Basic XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' }},
);
}
}
getNotifications() {
return this.load().map((data: any) => {
return data.notifications;
});
}
}
如您所见,我在刷新功能中再次运行服务(下面),但是新数据没有更新...除非我完全刷新网页以加载新的
this.onesignalData.getNotifications().subscribe((notifications) => {
this.notifications = notifications;
最初我认为在请求新数据之前Observable服务旧数据是一个问题,但是当我从等式中删除Observable时,我仍然遇到了同样的问题。你能看到我错过的东西吗?
答案 0 :(得分:1)
我仍然无法弄清楚数据存储在磁盘缓存中的原因,但我可以通过创建随机字符串并将其附加到GET请求网址来解决这个问题:
load(): any {
let timeStamp = +new Date();
return this.http.get('https://onesignal.com/api/v1/notifications?app_id=XXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXX&limit=50?tsp=' + timeStamp,
{ headers: { 'Authorization': 'Basic XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' }},
);
}
答案 1 :(得分:0)
1))您可以在ngOnChanges()中使用刷新功能,因此当您的数据发生变化时, ngOnChanges 将被调用。
2))您可以使用**双向绑定[(ngModel)] **来绑定HTML,因此每当您的数据发生更改时,它都会在视图中自动更新。像前 - >每当这个.notification数据被更改,它就会反映在你的视图中。
我个人更喜欢第一种方法,因为它更有说服力和容易。
ngOnChanges() - >>按照我在项目中使用的
ngOnChanges(changes: any) {
if (changes.dataSourceId != null && changes.dataSourceId.currentValue != null) {
if (changes.pageId != null && changes.pageId.currentValue != null) {
this.GetDataSource();
}
}