如何以 RxJS 方式通过索引在 Array 上删除和添加元素?
How can I remove and add element on Array by index in RxJS way?
所以,我有一个数组 "events":
let events = Rx.Observable.from([1,2,3,4,5,6,7,8,9]);
我可以添加(推送):
let add = function(number){
events = events.concat([number]);
}
我可以删除:
let remove = function(){
events = events.filter(event => {
return event != 3;
})
}
我的第一个问题:
如何以 "RxJS" 方式按索引删除和添加元素?
let removeByIndex = function(index){
//remove by index
}
let addByIndex = function(index){
//add by index
}
我的第二个问题:
我需要 "reinvent the wheel" 用于 RxJS 上 Array 的所有基本方法吗?
你的目的是什么?你的 Observable 只是一个发布者,它在你的应用程序的某个地方监听?
在这种情况下,您可以使用一个方法 publish
来推送您的新数组:
class EventStream {
private numbers$: Subject<number[]> = new Subject()
//or BehaviorSubject if you want a default value
publish(arrayNumberToPublish: number[]): void {
this.numbers$.next(arrayNumberToPublish)
}
listen(): Observable<number[]> {
return this.numbers$
}
}
在您的代码中,您收听流:new EventStream().listen().(...)
第二种可能是你想保留数组。当我想要存根 CRUD 时,我会使用它 API:
class EventManager {
private events: number[] = []
private events$: Subject<number[]> = new Subject()
//or BehaviorSubject if you want a default value
getAllEvents(): Observable<number[]> {
return this.events$
}
addEvent(index: number): void {
this.events = this.events.concat(index)
this.events$.next(this.events)
}
removeEvent(index: number): void {
this.events = this.events.filter(event => event !== index)
this.events$.next(this.events)
}
}
所以,我有一个数组 "events":
let events = Rx.Observable.from([1,2,3,4,5,6,7,8,9]);
我可以添加(推送):
let add = function(number){
events = events.concat([number]);
}
我可以删除:
let remove = function(){
events = events.filter(event => {
return event != 3;
})
}
我的第一个问题: 如何以 "RxJS" 方式按索引删除和添加元素?
let removeByIndex = function(index){
//remove by index
}
let addByIndex = function(index){
//add by index
}
我的第二个问题: 我需要 "reinvent the wheel" 用于 RxJS 上 Array 的所有基本方法吗?
你的目的是什么?你的 Observable 只是一个发布者,它在你的应用程序的某个地方监听?
在这种情况下,您可以使用一个方法 publish
来推送您的新数组:
class EventStream {
private numbers$: Subject<number[]> = new Subject()
//or BehaviorSubject if you want a default value
publish(arrayNumberToPublish: number[]): void {
this.numbers$.next(arrayNumberToPublish)
}
listen(): Observable<number[]> {
return this.numbers$
}
}
在您的代码中,您收听流:new EventStream().listen().(...)
第二种可能是你想保留数组。当我想要存根 CRUD 时,我会使用它 API:
class EventManager {
private events: number[] = []
private events$: Subject<number[]> = new Subject()
//or BehaviorSubject if you want a default value
getAllEvents(): Observable<number[]> {
return this.events$
}
addEvent(index: number): void {
this.events = this.events.concat(index)
this.events$.next(this.events)
}
removeEvent(index: number): void {
this.events = this.events.filter(event => event !== index)
this.events$.next(this.events)
}
}