【问题标题】:Getting undefined value from the json in console angular 5从控制台角度5中的json获取未定义的值
【发布时间】:2019-03-18 11:00:11
【问题描述】:

我有以下来自 api 的响应

 [
  {
    "Cinema_strName": "Cll, Kollam",
    "Cinema_strID": "CEWB",
    "Cinema_strBannerImg": "",
    "cinema_addr": "5th  Kollam",
    "cinema_loc": "<iframe src=\"https://www9550314\" width=\"600\" height=\"450\" frameborder=\"0\" style=\"border:0\" allowfullscreen></iframe>",
    "cinema_mob": 0
  },
  {
    "Cinema_strName": "Cs, Kollam",
    "Cinema_strID": "KEWB",
    "Cinema_strBannerImg": "",
    "cinema_addr": "Carlangara, Kollam, Kerala - 691581",
    "cinema_loc": "<iframe src=\"hsen!2sin49\" width=\"600\" height=\"450\" frameborder=\"0\" style=\"border:0\" allowfullscreen></iframe>",
    "cinema_mob": 0
  }
]

我想从 api 中获取cinema_loc,因为我正在执行以下代码

this.common.createAPIService('api/cinemas/List?CityName='+city, '').subscribe((result: any) => {
  if(result.length){
     this.cinema = result;
     this.loc = this.cinema.cinema_loc;      

     console.log(this.loc);


  }else{
      alert('Cinema not found');
  }

})

但它给了我未定义的价值。如果我写this.cinema[0].cinema_loc。我只会得到第一个响应 iframe。请帮忙。

对于@nikhil

<div class="col-md-9">
    <div class="map" *ngFor="let map of html">
    <div [innerHTML]="map"></div>
   </div>
</div>

【问题讨论】:

  • 你想如何读取/处理cinema_loc?
  • 我想在 html 中添加 iframe
  • 您想要一个特定的cinema_loc 还是在模板中的iframe 中显示所有这些?
  • 响应中的所有 iframe

标签: javascript angular angular5 ngfor


【解决方案1】:

this.cinema 是一个 array,而不是一个对象,如果您想访问需要遍历它们的所有元素。

在模板上显示使用ngFor如下,

<ul>
    <li *ngFor="let cineObj of cinema">
      {{ cineObj.cinema_loc }}
    </li>
</ul>

如果你只需要所有元素中的cinema_loc,你可以试试

let result = this.cinema.map(a => a.cinema_loc);

如果您想从中生成 HTML,请使用

let resultHtml = this.cinema.map(function(cineObj) {
return cineObj.cinema_loc;
}).join(', ');

【讨论】:

  • 我想追加为 html
【解决方案2】:

由于this.cinema 可以是数组或对象,因此如果它是数组,则需要对其进行迭代。当您尝试附加 html 时,您可以使用 Array.reduce 创建一个 html 字符串,然后根据要求附加它。尝试关注

let html = this.cinema.cinema_loc;
if(Array.isArray(this.cinema)) {
    html = this.cinema.reduce((a, {cinema_loc}) => a + cinema_loc, "");
}

【讨论】:

  • 不工作。对于单个响应,如果有多个类似于上面的响应,我会得到对象,我得到字符串
  • @SagarKodte - 你可以分享单个对象的响应吗?
  • 只需从上述响应中删除第二个 {}
  • @SagarKodte - 所以你的意思是你会收到一个对象而不是一个数组?
  • 是的,我使用 typeof 进行了检查
【解决方案3】:

您的代码中有几个问题 -

  1. 迭代 Cinemas 数组的方法错误。
  2. 消毒剂 - Angular 会报告不安全的 html,因此最好在使用前对其进行消毒。

创建清理方法

  safeHTML(content) {
    return this.sanitizer.bypassSecurityTrustHtml(content);
  }

在html中

<div class="map" *ngFor="let map of cinema">
  <div [innerHTML]="safeHTML(map.cinema_loc)"></div>
</div>

演示

演示在这里https://stackblitz.com/edit/angular-iframe-sanitizer

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-12
    相关资源
    最近更新 更多