首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从控制台angular 5中的json获取未定义的值

问从控制台angular 5中的json获取未定义的值
EN

Stack Overflow用户
提问于 2018-10-13 19:51:51
回答 3查看 156关注 0票数 0

我有以下来自api的响应

代码语言:javascript
复制
 [
  {
    "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
  }
]

我想要从下面的代码中获取cinema_loc

代码语言:javascript
复制
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

代码语言:javascript
复制
<div class="col-md-9">
    <div class="map" *ngFor="let map of html">
    <div [innerHTML]="map"></div>
   </div>
</div>
EN

回答 3

Stack Overflow用户

发布于 2018-10-13 19:55:48

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

代码语言:javascript
复制
let html = this.cinema.cinema_loc;
if(Array.isArray(this.cinema)) {
    html = this.cinema.reduce((a, {cinema_loc}) => a + cinema_loc, "");
}
票数 1
EN

Stack Overflow用户

发布于 2018-10-13 19:53:17

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

要在模板上显示,请使用ngFor,如下所示:

代码语言:javascript
复制
<ul>
    <li *ngFor="let cineObj of cinema">
      {{ cineObj.cinema_loc }}
    </li>
</ul>

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

代码语言:javascript
复制
let result = this.cinema.map(a => a.cinema_loc);

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

代码语言:javascript
复制
let resultHtml = this.cinema.map(function(cineObj) {
return cineObj.cinema_loc;
}).join(', ');
票数 0
EN

Stack Overflow用户

发布于 2018-10-13 20:50:17

在你的代码中有几个问题-

以错误的方式迭代影院array.

  • Sanitizer -
  1. 将报告不安全的html,因此最好在使用前对其进行杀毒。

创建要清理的方法

代码语言:javascript
复制
  safeHTML(content) {
    return this.sanitizer.bypassSecurityTrustHtml(content);
  }

在html中

代码语言:javascript
复制
<div class="map" *ngFor="let map of cinema">
  <div [innerHTML]="safeHTML(map.cinema_loc)"></div>
</div>

演示

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52792628

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档