如何获得 observable 的实际值

How to get actual value of observable

在服务中class 方法必须传递当前设备序列号。使用 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({});
        }
    }
}