Как отсортировать последние уведомления вверху? - PullRequest
1 голос
/ 11 июня 2019

Я разрабатываю приложение Ionic 3 с push-уведомлением OneSignal,

В настоящее время последнее уведомление отображается в нижней части списка, и у меня возникла проблема с сортировкой его вверху списка.

Я разместил свой код для экрана уведомлений ниже:

Пожалуйста, совет.

app.components.ts

initializeApp() {
    this.platform.ready().then(() => {
      // Okay, so the platform is ready and our plugins are available.
      // Here you can do any higher level native things you might need.
      this.statusBar.styleDefault();
      this.splashScreen.hide();
      if (isCordovaAvailable()) {
        this.oneSignal.startInit(oneSignalAppId, sender_id);
        this.oneSignal.inFocusDisplaying(this.oneSignal.OSInFocusDisplayOption.InAppAlert);
        this.oneSignal.handleNotificationReceived().subscribe(data => this.onPushReceived(data.payload));
        this.oneSignal.handleNotificationOpened().subscribe(data => this.onPushOpened(data.notification.payload));
        this.oneSignal.endInit();

      }
    });
  }

  private onPushReceived(payload: OSNotificationPayload) {
    this.notification.save(
      payload.title,
      payload.body,
      payload.notificationID,
      payload.launchURL,
      payload.bigPicture
    ).then(() => this.notification.showAlert(payload.title, payload.body));
  }

  private onPushOpened(payload: OSNotificationPayload) {
    this.notification.save(
      payload.title,
      payload.body,
      payload.notificationID,
      payload.launchURL,
      payload.bigPicture
    ).then(() => this.notification.showAlert(payload.title, payload.body));
  }

notifications.ts

  ngOnInit() {
    this.getNotifications();
  }

  getNotifications() {
    this.loading.showLoading();

    Promise.all([
      this.notification.all()
    ]).then(v => {
      this.notificationList = v[0];
      this.loading.dismissLoading();
    });
  }

  delete(item, i) {

    Promise.all([
      this.notification.delete(i),
    ]).then(() => {
      this.notificationList.splice(i, 1);
    });

  }

  clearAll() {
    Promise.all([
      this.notification.clear()
    ]).then(() => {
      this.notificationList = [];
    });
  }

notifications.html

<ion-content padding>
  <ion-title>
    Announcements
  </ion-title>

  <ion-list>

   <ion-item-sliding *ngFor="let item of notificationList; let i = index">
      <ion-item (click)="redirect(item?.launchURL)">
        <img src="{{ item?.bigPicture }}" style="display:block;" />
        <h2>{{ item?.title }}</h2>
        <p>{{ item?.message }}</p>
        <small>{{ item?.created_at }}</small>
      </ion-item>
      <ion-item-options>
        <button ion-button color="light" (click)="delete(item, i)">Delete</button>
      </ion-item-options>
    </ion-item-sliding>

    <button *ngIf="notificationList.length > 0" ion-button color="danger" (click)="clearAll()" full>Delete All</button>

  </ion-list>

</ion-content>

1 Ответ

1 голос
/ 11 июня 2019

Самым быстрым способом может быть Array.reverse ()

  getNotifications() {
    this.loading.showLoading();

    Promise.all([
      this.notification.all()
    ]).then(v => {
      this.notificationList = v[0];
      this.notificationList = this.notificationList.reverse();
      this.loading.dismissLoading();
    });
  }

Более сильный подход заключается в создании службы кэширования для кэширования ваших старых уведомлений и уведомлений.сервис с использованием Rxjs Observables .Вы можете подписаться на изменения в вашем списке уведомлений и публиковать обновления при каждом изменении данных.Вот выдержка из службы уведомлений, которую мы написали в моей компании, с несколькими незначительными изменениями, чтобы соответствовать структуре ваших notificationsList[] из Item s:

// ./services/notificationsList.service.ts

import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
// import { LocalStorageService } from './localstorage.service'
import { Observable } from 'rxjs/Observable';
import _ from 'lodash';

export interface Item {
  itemId: string;
  created_at: number;
  message: string;
  title: string;
};

@Injectable()
export class NotificationList {
  private notificationsSubject: BehaviorSubject<Item[]>;
  public notificationList: Observable<Item[]>;
  // you can create a LocalStorageService for your cache
  private notificationsCache: LocalStorageService<Item[]> = new LocalStorageService<Notification[]>('notifications', []);

  constructor() {
    this.notificationsSubject = new BehaviorSubject<Item[]>(this.notificationsCache.get());
    this.notifications = this.notificationsSubject.distinctUntilChanged(_.isEqual).publishReplay(1).refCount();
    this.notifications.subscribe(notifications => this.notificationsCache.set(notifications));
  }

 // etc ...

}

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...