如何分配给管道中的变量true?

How to assign to variable true in pipe?

如果 id 为空,我希望变量 x 为真。我会使用 if 和 else 但不能在管道中使用。请帮助我。

  private x = false;
  private y = false;

ngOnInit() {
    this.subscribe = this.route.params.pipe(
    map(({ id }) => id),
    filter(id => !!id), // <---- here
    switchMap((id: string) => 
     this.shippingService.getShippingById(id)))
  .subscribe(
    res => {
      this.shippingData = res;
      this.y= true;
    },
    err => this.error = err.error,
  );
}

您可以在过滤器之前使用 tap 运算符:

ngOnInit() {
    this.subscribe = this.route.params.pipe(
    map(({ id }) => id),
    tap((val) => { if (val === null) this.x = true }),
    filter(id => !!id),
    switchMap((id: string) => 
     this.shippingService.getShippingById(id)))
  .subscribe(
    res => {
      this.shippingData = res;
      this.y= true;
    },
    err => this.error = err.error,
  );
}