我有一個可觀察的
imageOptions$: Observable<BoundImagesToProject[]> = this.imagesService
.getBoundImages({ projectId: this.projectId })
.pipe(map((images) => (images.data)));
在模板中我像使用它一樣
<div class="form-field input-group">
<label for="image">Image</label>
<mat-select id="image" class="select--full-width" placeholder="Image" formControlName="image">
<mat-option *ngFor="let image of imageOptions$ | async" [value]="image.imageId">
{{ image.name }}
</mat-option>
</mat-select>
<mat-error *ngIf="createVmForm.get('image').getError('required') && createVmForm.get('image').dirty"
>Field is required</mat-error
>
</div>
現在我想在 TS 檔案中使用可觀察的 imagesOptions$,例如
this.imageChangeSubscription = this.createVmForm.get('image').valueChanges.subscribe((value) => {
this.selectedImageVolumeSize = this.imagesOptions$ // get array value and match id and get the size.
如果它是一個陣列,它會像
this.selectedImageVolumeSize = this.images.find((image) => image.imageId === value).size;
我想在不訂閱 imageOptions$ 可觀察的 imageChangeSubscription 的情況下做到這一點,以避免在側面訂閱中訂閱并且不使用 TS 檔案中的額外屬性
有什么辦法嗎?
uj5u.com熱心網友回復:
您可以使用switchMap()來避免嵌套訂閱。但是您應該更新,以便它可以與使用運營商imagesOptions$的多個訂閱者共享其最新值。shareReplay()
imageOptions$: Observable<BoundImagesToProject[]> = this.imagesService
.getBoundImages({ projectId: this.projectId })
.pipe(
map(({data}) => data),
shareReplay(1)
);
然后在您的訂閱中,從中獲取最新值imageOptions$以找到您的尺寸。
this.imageChangeSubscription = this.createVmForm
.get('image').valueChanges
.pipe(
switchMap(value => this.imagesOptions$
.pipe(
map(images => images.find(({imageId}) => imageId===value ))
)
)
).subscribe();
uj5u.com熱心網友回復:
我喜歡@Joshua McCarthy 提供的答案,但您根本不需要訂閱,您可以獲得“更清潔”(取決于消費者的角度)版本。
感謝關于shareReplay(1)避免額外副作用的宣告(它們通常是 API 呼叫,導致不希望的網路消耗)。我強烈建議您將其應用于可觀察的影像選項。
然后我將繼續創建另一個可觀察的:
import { combineLatest, shareReplay } from 'rxjs/operators'
@Component({...})
export class YourComponent {
...
...
selectedImageVolumeSize$ = combineLatest([this.createVmForm['image'].valueChanges, this.imagesOptions$]).pipe(
map(([selectedImageId, imageOptions] => imageOptions.find(item => item.id === selectedImageId)
)
constructor(...){}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/414461.html
標籤:
下一篇:為反應組件傳播道具
