У меня проблема с шаблоном, который я использую в angular 4. Этот шаблон реализует систему уведомлений, в которую вы можете добавлять новые уведомления, но в документации не указано, как можно удалить элементы наблюдателя ReplaySubject.
Шаблон реализует это как услугу следующим образом:
private notificationsList: Notification[] = [];
// a stream that publishes new notifications only once
public newNotifications: Subject<Notification> = new Subject<Notification>();
// `notifications` is a stream that emits an array of the most up to date notifications
public notifications: ReplaySubject<Notification[]> =
new ReplaySubject<Notification[]>(1);
// `updates` receives _operations_ to be applied to our `notifications`
// it's a way we can perform changes on *all* notifications (that are currently
// stored in `notifications`)
public updates: Subject<any> = new Subject<any>();
// action streams
public create: Subject<Notification> = new Subject<Notification>();
// public markThreadAsRead: Subject<any> = new Subject<any>();
constructor() {
// recois des operation, et les fais sur la liste interne, puis diffuse le
// resultat sur notifications
this.updates.subscribe((ope) => {
this.notificationsList = ope(this.notificationsList);
console.info(this.notificationsList);
this.notifications.next(this.notificationsList);
});
this.newNotifications
.map(function(notification: Notification): INotificationsOperation {
return (notifications: Notification[]) => {
return notifications.concat(notification);
};
})
.subscribe(this.updates);
}
// an imperative function call to this action stream
public addNotification(notification: Notification): void {
this.newNotifications.next(notification);
}
Я пытаюсь спросить владельца, как я могу удалить фактический элемент списка уведомлений, но он просто сказал мне, что я могу получить доступ к «уведомлениям», чтобы получить его последнюю версию. Но не говоря уже о том, как я могу удалить элемент списка.
Кто-то что-то знает?
Спасибо!
Если вы хотите игнорировать сохраненный элемент, вы можете просто использовать функцию пропуска: replaySubject$.skip(1).subscribe()
Итак, если вы хотите удалить один элемент из «notificationsList», например, первый notificationsList [0], как бы вы реализовали функцию для этого?
Итак, ваша проблема - «как удалить элемент из списка»? В этом случае: Если вы хотите сохранить размер списка без изменений: del notificationList[0] Если вы хотите удалить элемент и изменить масштаб списка: notificationList.splice(0,1) // delete 1 element starting from 0th position and resize
Да, я действительно пытаюсь удалить один элемент списка, но код, который я публикую ранее, является службой шаблона в angular, а список уведомлений является частным, поэтому мне нужно сделать это из общедоступного свойства newNotifications, notifications, updates или Создайте. Я действительно не знаю, как работает тема rxjs, тема воспроизведения, и не могу понять, как я могу это сделать. А пока я делаю что-то не очень хорошее: создаю новый список снаружи и использую this.notifServ.notifications.next (newNotif); чтобы обновить список, он работает, но не очень хорошо.



![Безумие обратных вызовов в javascript [JS]](https://i.imgur.com/WsjO6zJb.png)


Я добавил публичную функцию, которую вы можете использовать. Я добавил комментарий, чтобы вы могли видеть, какую часть кода вы можете изменить, если вы, например, хотите удалить элементы по имени или не хотите изменять размер списка. Пояснение в конце моего поста.
private notificationsList: Notification[] = [];
// a stream that publishes new notifications only once
public newNotifications: Subject<Notification> = new Subject<Notification>();
public removeNotificationByIndex$ : Subject<number> = new Subject<number>();
// `notifications` is a stream that emits an array of the most up to date notifications
public notifications: ReplaySubject<Notification[]> =
new ReplaySubject<Notification[]>(1);
// `updates` receives _operations_ to be applied to our `notifications`
// it's a way we can perform changes on *all* notifications (that are currently
// stored in `notifications`)
public updates: Subject<any> = new Subject<any>();
// action streams
public create: Subject<Notification> = new Subject<Notification>();
// public markThreadAsRead: Subject<any> = new Subject<any>();
constructor() {
// recois des operation, et les fais sur la liste interne, puis diffuse le
// resultat sur notifications
this.updates.subscribe((ope) => {
this.notificationsList = ope(this.notificationsList);
console.info(this.notificationsList);
this.notifications.next(this.notificationsList);
});
this.newNotifications
.map(function(notification: Notification): INotificationsOperation {
return (notifications: Notification[]) => {
return notifications.concat(notification);
};
})
.subscribe(this.updates);
this.removeNotificationByIndex$
.map(function(index: number){
return (notifications: Notification[]) => {
// >>>> DELETE METHOD IS TO BE DEFINED DOWN HERE !
notifications.splice(index,1);
// >>>> DELETE METHOD IS TO BE DEFINED UP HERE !
return notifications
};
})
.subscribe(this.updates);
}
// an imperative function call to this action stream
public addNotification(notification: Notification): void {
this.newNotifications.next(notification);
}
// delete the element in the "index" position of the list.
// /!\ Resizes the list
public removeNotificationsByIndex(index: number): void {
this.removeNotificationByIndex$.next(index);
}
Какие изменения?
public removeNotificationByIndex$ : Subject<number> = new Subject<number>();
Этот субъект получит (асинхронно) индекс и запустит процесс, использующий этот индекс.
this.removeNotificationByIndex$
.map(function(index: number){
return (notifications: Notification[]) => {
// >>>> DELETE METHOD IS TO BE DEFINED DOWN HERE !
notifications.splice(index,1);
// >>>> DELETE METHOD IS TO BE DEFINED UP HERE !
return notifications
};
})
.subscribe(this.updates);
Когда создается индекс (т. Е. Вы используете связанную императивную функцию), из него создается функция (стрелочная функция ES6). Это оно :
(notifications: Notification[]) => {
// >>>> DELETE METHOD IS TO BE DEFINED DOWN HERE !
notifications.splice(index,1);
// >>>> DELETE METHOD IS TO BE DEFINED UP HERE !
return notifications
};
Эта функция передается в this.update, который применяет ее. В данном контексте этой функцией является ope. при получении this.notificationList изменяется следующим образом:
this.notificationsList = ope(this.notificationsList);
Наконец, этот новый список публикуется в ReplaySubject notifications:
this.notifications.next(this.notificationsList);
Которые распространяют этот новый список на всех его подписчиков.
Вуаля :). Удачи !
Рад, если помогло!
ReplaySubject содержит ваше последнее испущенное значение, в вашем случае последнее с момента создания объекта с помощью (1), поэтому вы не можете удалить уведомление из самого ReplaySubject, но вы можете получить значение из него, и если вам нравится ID или что-то еще из уведомления, вы можете просто удалить его вручную из массива и передать новое значение в ReplaySubject.