[英]How to get actual value of observable
在服務類中,方法必須傳遞當前設備的serialNumber。 使用ngrx,可以預訂device $以獲得實際的設備,但這並不好。 在這種情況下,最佳做法是什么?
@Injectable()
export class DeviceService {
public device$: Observable<Device>;
public device: Device; // feels 'redundant'
constructor(private http: HttpClient,
private store: Store<DeviceState>,) {
this.device$ = this.store.select(DeviceSelectors.getCurrentDevice);
this.device$.subscribe((device: Device) => {
this.device = device; // feels bad
});
}
regenerate() : Observable<Object> {
if (environment.production) {
const url = `${environment.url}/devices/${this.device.serialNumber}/regenerate`;
return this.http.get(url) as Observable<Object>;
} else {
return of({});
}
}
}
您可以使用mergeMap實現所需的功能:
@Injectable()
export class DeviceService {
public device$: Observable<Device>;
constructor(private http: HttpClient,
private store: Store<DeviceState>,) {
this.device$ = this.store.select(DeviceSelectors.getCurrentDevice);
}
regenerate() : Observable<Object> {
if (environment.production) {
return this.device$
.pipe(
first(),
mergeMap(device => this.http.get(`${environment.url}/devices/${device.serialNumber}/regenerate`))
);
} else {
return of({});
}
}
}
@NielsSteenbeek,通常我要做的是從存儲中即時獲取值(調用regenerate()時),您可以使用flatMap來存檔所需的內容
@Injectable()
export class DeviceService {
constructor(private http: HttpClient, private store: Store<DeviceState>,) {}
regenerate() : Observable<Object> {
if (environment.production) {
return this.store.select(DeviceSelectors.getCurrentDevice)
.pipe(
first(),
flatMap(device => this.http.get(`${environment.url}/devices/${device.serialNumber}/regenerate`))
);
} else {
return of({});
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.