【问题标题】:core.mjs:6484 ERROR TypeError: Cannot read properties of undefined (reading 'name')core.mjs:6484 错误 TypeError:无法读取未定义的属性(读取 \'name\')
【发布时间】:2023-01-30 16:13:12
【问题描述】:

在 console.log 中,我有一条错误消息,但我无法解决这个问题......

这是错误信息

core.mjs:6484 ERROR TypeError: Cannot read properties of undefined (reading 'name')

我应该如何在下面声明name

 ...
    <ng-container *ngIf="dta && dta.PP">
 ...

HTML

<ng-container *ngIf="dta && dta.PP  ">
  <div class="card" style="width: 60%">
    <div class="card-body">
      <div class="row">
        <div class="col">
          <table class="table table-hover table-striped spaceLeft">
            <tbody>
              <tr>
                <th>Year</th>
                <td>{{ fiscalYear }}</td>
              </tr>
              <tr>
                <th>Country</th>
                <td>{{ selectedCountry.name }}</td>
              </tr>
              <tr>
                <th>Register</th>
                <td>{{ registreNational }}</td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>
    </div>
  </div>
</ng-container>

TS

selectedCountry: Country;

ngOnInit(): void {
    ...

    this.service.getPaysDta().pipe(
        takeUntil(this.unsubscribe$)
    ).subscribe((countries) => {
        this.countries = countries;

        let selectedCountry = this.countries.find(c => c.id == this.country);
        if (selectedCountry) {
            this.selectedCountry = selectedCountry;
        }
    });

}

国家.ts

export class Country {
    id : string;
    name: string;

}

我不知道如何正确声明变量name...:S

谢谢您的帮助。

【问题讨论】:

    标签: angular


    【解决方案1】:

    selectedCountry 默认是未定义的,它只会在异步的getPaysDta() 订阅回调中被赋值。

    在 HTML 中,您将字符串插入 {{ selectedCountry.name }}。最初它将尝试访问 undefinedname 属性,因此出现错误消息。

    您可以通过使用 *ngIf 包装字符串插值来非常轻松地解决此问题。

    例子:

    <td>
    <span *ngIf="selectedCountry">{{ selectedCountry.name }}</span>
    </td>
    

    【讨论】:

    • 谢谢内森的解释。有用 :-)
    【解决方案2】:

    非常感谢!它也对我有用

    【讨论】:

    • Alexander Repollo,请不要添加谢谢作为答案。它们实际上并没有提供问题的答案,并且可能被未来的访问者视为噪音。一旦你earn足够reputation,你将获得你喜欢的upvote answers的特权。这样问题的未来访问者将看到对该答案的更高投票计数,并且回答者也将获得声誉点数奖励。参见Why is voting important
    猜你喜欢
    • 2022-11-06
    • 2022-12-24
    • 2023-02-26
    • 2022-07-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-05
    相关资源
    最近更新 更多