我有一個用戶陣列主題
private _currentHeroes = new Subject<Hero[]>();
currentHeroes = this._currentHeroes.asObservable();
- 我的目標是只編輯陣列的 1 個元素而不訂閱
在我的服務中為用戶加電的功能
powerUp(id: number) {
return this.http
.post<Hero>(environment.apiUrl 'heroes/powerUp/' id, {})
.pipe(
tap((updatedHero: Hero) => {
this._currentHeroes.next(
// I would like to edit the specific element in the array and than sort them by the power.
);
})
);
}
在我的服務中洗掉用戶的功能
delete(id: number) {
return this.http.delete<Hero>(environment.apiUrl 'heroes/' id).pipe(
tap((deletedHero) => {
this._currentHeroes.next(
// Here I delete the specific element from the array
);
})
);
}
如果主題是 BehaviorSubject 那么我會這樣做:
powerUp(id: number) {
return this.http
.post<Hero>(environment.apiUrl 'heroes/powerUp/' id, {})
.pipe(
tap((updatedHero: Hero) => {
this._currentHeroes.next(
this._currentHeroes.value
.map((hero: Hero) =>
hero.id === updatedHero.id ? updatedHero : hero
)
.sort((a, b) => a.currentPower - b.currentPower)
);
})
);
}
delete(id: number) {
return this.http.delete<Hero>(environment.apiUrl 'heroes/' id).pipe(
tap((deletedHero) => {
this._currentHeroes.next(
this._currentHeroes.value.filter(
(hero: Hero) => hero.id !== deletedHero.id
)
);
})
);
}
但我的目標是在使用 Subject 而不是 BehaviorSubject 時實作相同的目標。
我嘗試獲取主題的值,但這是不可能的,因為它是一個主題。我嘗試在線搜索,但不幸的是,我沒有找到滿足我需求的任何有用的解決方案。
有沒有人遇到這個問題?或者怎么解決?
uj5u.com熱心網友回復:
我想您正在處理一項服務,然后您可以在服務屬性中獲得需要修改的陣列的參考。
heroes = [];
然后,在每次操作之后,您都可以修改該值,然后使用主題或行為主題或您想要使用的任何內容發出。
powerUp(id: number) {
return this.http
.post<Hero>(environment.apiUrl 'heroes/powerUp/' id, {})
.pipe(
tap((updatedHero: Hero) => {
//modify data reference, to add, update or delete value
// in this case modify with powerup
this.heroes = this.heroes
.map((hero: Hero) =>
hero.id === updatedHero.id ? updatedHero : hero
)
.sort((a, b) => a.currentPower - b.currentPower)
// emit the resuelt after every operation
this._currentHeroes.next(
this.herores
);
})
);
}
請記住,您必須訂閱每個回傳 observable 的操作,就像您在代碼中顯示的那樣。
// for example to hero with id 2
this.yourHeroService.powerUp(2).subscribe()
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/376686.html
上一篇:“Enter”在VSCodeforPython中不起作用
下一篇:如何從我的物件創建一個數字陣列?
