检查一个可能为undefined的Angular对象的类型。

huangapple go评论72阅读模式
英文:

check the type of an Angular object that can be undefined as well

问题

我正在学习Angular,我想编写一个方法,如果对象的类型是`Dog`(它具有`woof`属性),则返回`true`。

到目前为止,我有以下内容:

    export class SomeClass {
       public animal?: Dog | Cat;
       ...
       public isDog() {
        return 'woof' in this.animal;  <-- 对象可能为 'undefined'
      }
    }

然后根据对象的类型显示内容的方式如下:

    <div *ngIf="isDog(); then dogCardTemplate else catCardTemplate"></div>

我的问题是`this.animal`可能为未定义,并出现以下错误:

    对象可能为 'undefined'。

请问您是否能帮助我以尽可能少的代码行数简单解决这个问题?
英文:

I am learning Angular and I would like to write a method that returns true if the type of the object is Dog (it has a woof property).

This is what I have so far:

export class SomeClass {
   public animal?: Dog | Cat;
   ...
   public isDog() {
    return &#39;woof&#39; in this.animal;  &lt;-- Object is possibly &#39;undefined&#39;
  }
}

Then I show the content based on the type of the object this way:

&lt;div *ngIf=&quot;isDog(); then dogCardTemplate else catCardTemplate&quot;&gt;&lt;/div&gt;

My problem is that this.animal can be undefined and the following error appears:

Object is possibly &#39;undefined&#39;.

Could you please help me to solve this in a simple way with as less code line as possible?

答案1

得分: 0

以下是翻译好的部分:

export class SomeClass {
   public animal?: Dog | Cat;
   
   public isDog() {
      return  this.animal // 首先检查是否已定义
           && 'woof' in this.animal; // 稍后检查动物类型
   }

}

为什么?

因为属性是可选的,我们需要检查它是否已定义,只有在那之后才能检查它是否是一只狗。

注意:如果您想检查它是否是一只猫,您需要重复未定义的检查。

英文:

The proper way to check if is the following:

export class SomeClass {
   public animal?: Dog | Cat;
   
   public isDog() {
      return  this.animal // check to see if its defined first
           &amp;&amp; &#39;woof&#39; in this.animal; // animal type check later
   }

}

Why?

Well since the property is optional, we need to make a check to see if it is defined and only after that can we make a check for if its a dog.

Note: if you want to check that it is a cat, you will need to repeat the undefined check.

答案2

得分: 0

我建议你不要直接在HTML中使用'get'方法。然后,如果你百分之百确定这个动物不会是undefined,?可以被移除。

public animal: Dog | Cat;

或者可以参考IDK4real的答案。

英文:

i sugest you to not use directly 'get' method on html https://stackoverflow.com/questions/55051164/using-setters-and-getter-variables-on-html-angular-component

Then if you are 100% sure this animal cannot be undefined, ? can be removed

public animal: Dog | Cat;

Or follow the IDK4real answer

huangapple
  • 本文由 发表于 2023年6月19日 18:52:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/76505930.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定