我正在嘗試將服務層的回傳傳遞給組件。
我與 api 連接的服務:
public getPerfilNew$(): Observable<PerfilInvestidor> {
return this.http.get<PerfilInvestidor>(`${environment.api.basePosicaoConsolidada}/consolidado`)
.pipe(
map(res => res),
shareReplay(1),
catchError(err => {
console.log('Error in perfil', err);
return throwError(err);
})
)
}
負責邏輯的層,當幾個組件依賴此資訊時,我會使用它:
perfilFailed$ = this.api.getPerfilNew$().pipe(
map(perfil => {
this.perfilInvestidor = perfil
this.perfilFailed = this.perfilInvestidor.status ? true : false;
})
)
在我的組件中:我以兩種方式嘗試過:
public loadData() {
this.coreState.perfilCliente$.subscribe(res => {
console.log(res)
})
}

幾個組件需要知道this.perfilFailed是false還是true,所以我不想在組件中而是在核心狀態服務中這樣做
有了這么多的可觀察量,我會損害記憶體嗎?我愿意接受建議
uj5u.com熱心網友回復:
1. 問題
這里沒有足夠的代碼來確切了解發生了什么。但乍一看,從我的角度來看,它看起來像是一種競爭條件:
您必須了解 Subject 是如何作業的。
const sub = new Subject();
sub.next(1);
// If you subscribe here like:
sub.subscribe(a => console.log(a))
// Nothing will happen because Subject does not preserve the old values
但如果你這樣做:
const sub = new Subject();
// If you subscribe here like:
sub.subscribe(a => console.log(a))
sub.next(1);
// You will get a print in a console since you emitted the value after you subscribed on the stream.
在您的情況下,您似乎在主題已經發出值之后訂閱了主題。
還:
this.perfilClient$.subscribe(res => {
您正在訂閱 this.perfilClient$,但我看不到您在該流上的何處發出值?
因此,如果您無法在發出值之前同步訂閱主題的內容,則可以使用 ReplaySubject 或 BehaviourSubject
2. 問題 你只有幾個可觀察的,并不多。但是有一些反模式,例如:
- 嵌套訂閱
- 訂閱回呼函式為空等。
RXJs 的主要內容是盡可能避免副作用。
uj5u.com熱心網友回復:
我不知道this.perfilClient$你在你的 中使用的是什么getPerfilFailed(),但我不明白為什么你不能做所有需要的事情并將它直接分配給一個 observable?所以在你的服務中是這樣的:
constructor(private api: HomeGuardService....) { }
perfilFailed$ = this.api.getPerfilNew$().pipe(
map(perfil => perfil.status)
);
然后您可以訂閱perfilFailed$組件中的變數。
喜歡...
public loadData() {
this.coreState.perfilFailed$.subscribe(res => {
console.log(res)
})
}
記得退訂哦!
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/348012.html
標籤:javascript 有角的 打字稿 rxjs
