【问题标题】:Error with left hand side of assignment expression Angular 2+赋值表达式 Angular 2+ 左侧的错误
【发布时间】:2019-02-22 04:21:33
【问题描述】:

我目前正在尝试过滤从硬编码数据返回的 JSON。在我的组件中,我的代码目前如下所示:

export class CtaComponent implements OnInit {
  @Input() ctaId: string;

  public ctaCards: CtaCards.ICtaCard[];
  constructor(private ctaService: CtaService) {
  }

  ngOnInit() {
    if (this.ctaId !== undefined) {
      this.ctaService.getCtaCards(this.ctaId)
        .subscribe(x => {
          this.ctaCards.find(z => z.id == this.ctaId) = x
        })
    }
  }
}

我相信您可以看到,find 行不起作用。 ctaId 是用于过滤 JSON id 的 id。然而,find 的代码被突出显示为一个错误,并说The left hand-side assignment expression must be a variable or property access. 我对 Angular 还是很陌生,所以这可能只是一些明显的错误。我的研究似乎对我没有任何帮助。

我的服务如下所示:

export class CtaService {
  private ctaCard: BehaviorSubject<CtaCards.ICtaCard[]>
  private productUrl = 'src/assets/cta.json'

  constructor(private http: HttpClient) {}

  public getCtaCards(id: string): BehaviorSubject<CtaCards.ICtaCard[]{
    if (id) {
      this.ctaCard = new BehaviorSubject<CtaCards.ICtaCard[]>(null);

      this.http.get(this.productUrl).pipe(
        retry(3)
      )
        .subscribe((x: CtaCards.ICtaCard[]) => this.ctaCard.next(x))
    }
    return this.ctaCard;
  }
}

【问题讨论】:

  • 这里的z 是什么?
  • @HarunurRashid 它是Cta card,所以在这种情况下,它会得到Cta Cardid
  • @FrankFajardo 它稍后会使用它,一开始的检查只是为了检查。
  • 这段代码没有意义:this.ctaCards.find(z =&gt; z.id == this.ctaId) = x。我想你的意思是this.ctaCards.find(z =&gt; z.id == this.ctaId) == xthis.ctaCards.find(z =&gt; z.id == this.ctaId) === x。但话又说回来,这是一个合乎逻辑的检查。之后会发生什么?
  • @FrankFajardo 你是对的,我会去重新评估我的代码。

标签: angular filter


【解决方案1】:

您正试图找到一些ctaCard 并将x 分配给它。你不能这样做,因为,

find 返回:

数组中满足提供的测试函数的第一个元素的值;否则,返回未定义。
而且您不能分配价值而不是变量。你正在尝试做这样的事情:

var a = 5;
5 = 10;

这没有任何意义。

您可以使用findIndex,如下所示:

index = this.ctaCards.findIndex(z => z.id == this.ctaId);
this.ctaCards[index] = x;

【讨论】:

  • 确实有道理,您对我如何修复我的代码有什么建议吗?
  • 更新了我的答案。您可以通过最后两行代码修复您的代码
  • @DanielBailey,如果它适合你,请告诉我......?更多参考可以阅读geeksforgeeks.org/lvalue-and-rvalue-in-c-language
  • 别忘了处理异常。当没有找到数据时,索引可以是 -1 :)
猜你喜欢
  • 1970-01-01
  • 2018-10-08
  • 2016-11-24
  • 1970-01-01
  • 2012-07-26
  • 2017-04-26
  • 2021-05-07
  • 2020-12-06
  • 2018-05-04
相关资源
最近更新 更多