简体   繁体   English

仅读取一个记录(json数组)的最佳实践

[英]Best practice to read just ONE record (json-array)

I am reading the result of a REST-method (observable) that contains only one element by convention. 我正在阅读一种REST方法(可观察)的结果,该方法按照惯例仅包含一个元素。 Actually my code works (the data is display) but in the browser's console, I am receiving ERROR TypeError: Cannot read property 'primaryHashtag' of undefined. 实际上我的代码可以工作(显示数据),但是在浏览器的控制台中,我收到错误TypeError:无法读取未定义的属性“ primaryHashtag”。

Is it good practice to access the data as shown below (specifing element 0) or should I copy the data into another wrapper object? 如下所示访问数据(指定元素0)是一种好习惯还是应该将数据复制到另一个包装对象中? (which might just shift the problem) (这可能会解决问题)

Is it good practice to access the data like this? 像这样访问数据是否是一种好习惯?

<div class="thumbnail">
  <img src="http://placehold.it/320x150">
  <div class="caption">
    <h4 class="float-right">{{article[0].primaryHashtag}}</h4>
    <p>{{article[0].comments}}</p>
  </div>
</div>

You should always check for null and give it empty state. 您应该始终检查null并将其设置为空状态。 like below 像下面

<div class="thumbnail" *ngIf="article && article[0]">
<img src="http://placehold.it/320x150">
 <div class="caption">
  <h4 class="float-right">{{article[0].primaryHashtag}}</h4>
  <p>{{article[0].comments}}</p>
 </div>
</div>
<div *ngIf="!article || !article[0]">
 <empty-state-component>    </empty-state-component>
</div>

Else if you dont want empty state you just want check for null you can do 否则,如果您不希望为空状态,则只想检查null即可

<h4 class="float-right">{{article[0]?.primaryHashtag}}</h4>
<p>{{article[0]?.comments}}</p>

You can use RxJS operators and to improve your code use angular async pipe : 您可以使用RxJS运算符,并使用角度async管道来改善代码:

In your component : 在您的组件中:

this.article$ = this.http.get<any[]>("YOUR_URI").pipe(
   map(res => res[0])
)

In your template 在您的模板中

<div class="thumbnail" #ngIf="article$ | async as article">
  <img src="http://placehold.it/320x150">
  <div class="caption">
    <h4 class="float-right">{{article.primaryHashtag}}</h4>
    <p>{{article.comments}}</p>
  </div>
</div>

You can check whether the array contains data thought *ngIf statement to avoid undefined : 您可以检查数组是否包含以*ngIf语句表示的数据,以避免undefined

<div class="thumbnail">
  <div 
      *ngIf="article && article.length > 0" 
       class="caption">
    <h4 class="float-right" >{{ article[0].primaryHashtag }}</h4>
    <p>{{article[0].comments}}</p>
  </div>
</div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM