在服务类中,方法必须传递当前设备的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({});
}
}
}
答案 0 :(得分:4)
您可以使用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({});
}
}
}
答案 1 :(得分:1)
@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({});
}
}
}