【问题标题】:How to assign to variable true in pipe?如何在管道中分配给变量true?
【发布时间】:2020-12-23 01:22:11
【问题描述】:

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

【问题讨论】:

    标签: angular typescript filter pipe


    【解决方案1】:

    您可以在过滤器之前使用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,
      );
    }
    

    【讨论】:

    • 在这个解决方案中,"if' 用红色下划线并且有信息:'{' 预期,最后的")" 用红色下划线并且有信息:';'预期。如何解决?
    • 你可以这样做:tap((val) =&gt; { if (val === null) this.x = true }),,我还编辑了答案以更准确
    猜你喜欢
    • 2022-08-14
    • 1970-01-01
    • 1970-01-01
    • 2021-02-04
    • 1970-01-01
    • 1970-01-01
    • 2017-08-15
    • 2016-06-26
    • 1970-01-01
    相关资源
    最近更新 更多