首页 > 解决方案 > How to assign to variable true in pipe?

问题描述

If id is null I want variable x to be true. I would use if and else but can't do that in pipe. Please help me.

  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,
  );
}

标签: angulartypescriptfilterpipe

解决方案


您可以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,
  );
}

推荐阅读