javascript - Angular4 - 如何检查 Twitter 媒体 key 是否存在或未定义

标签 javascript json angular twitter

基于 this question 构建...我希望能够返回帐户时间线的最后 5 条推文,以及它们可能附加的任何图像。我的问题是,当对 Twitter 的 API 进行搜索调用时,返回的一些推文 JSON 根本不包含Entity.media.media_url 键。如果我将Entity.media.media_url 作为调用的一部分,并且推文不包含任何附件,则会破坏整个请求,并且根本不会呈现任何推文。在呈现请求之前是否可以检查推文是否包含该信息?例如,在尝试解析这两条推文时:

tweet1(无图像)

...
"created_at":"Tue Aug 29 17:30:29 +0000 2017"
"entities": {
   "hashtags": [{...},{...}],
   "symbols": [],
   ...
  },
  "metadata":{...},
  "user": {...},
  ...
}

tweet2(包含附加图像)

...
"created_at":"Mon Aug 28 12:30:31 +0000 2017"
"entities": {
   "hashtags": [{...},{...}],
   "media":[ {"id":..., "id_str":"...", ..., "media_url": "...", 
   "media_url_https": "..."]
   "symbols": [],
   ...
  },
  "metadata":{...},
  "user": {...},
  ...
}

我有一个 node.js 后端处理搜索调用的大部分工作(在 this tutorial 之后), 我的 tweets.component.ts 获取元素并将它们分配给要在前端插值的变量。

tweets.component.ts

import { Component, OnInit, Input } from '@angular/core';
import { NO_ERRORS_SCHEMA } from '@angular/core';
import { Ng4TwitterTimelineModule } from 'ng4-twitter-timeline/lib/index';
import { Ng4TwitterTimelineService } from 'ng4-twitter-timeline/lib/index';
import { Http, Headers } from '@angular/http';
import { NgModel, NgForm, FormsModule } from '@angular/forms';

@Component({
  selector: 'app-tweets',
  templateUrl: './tweets.component.html',
  styleUrls: ['./tweets.component.scss'],
})
export class TweetsComponent implements OnInit {

  searchquery = 'musechat';
  tweetsdata;
  screen_name;
  user;
  profile_img_url;
  user_id;

  asset_img_url;

  // icon = this.tweetsdata[0].user.entities.profile_image_url;
   constructor (private http: Http) {}

  ngOnInit() {
    this.makecall();
    this.searchcall();
  }

  makecall() {
    const headers = new Headers();

    headers.append('Content-Type', 'application/X-www-form-urlencoded');

    this.http.post('http://localhost:3000/authorize', {headers: headers}).subscribe((res) => {
      // console.log(res);
    });
  }

  searchcall() {
    const headers = new Headers();
    // const searchterm = 'query=' + this.searchquery;
    const searchterm = 'query=from%3Adailymuse%20%23' + this.searchquery;


    headers.append('Content-Type', 'application/X-www-form-urlencoded');

    this.http.post('http://localhost:3000/search', searchterm, {headers: headers}).subscribe((res) => {
      this.tweetsdata = [
        res.json().data.statuses[0],
        res.json().data.statuses[1],
        res.json().data.statuses[2],
        res.json().data.statuses[3],
        res.json().data.statuses[4],
        // res.json().data.statuses[5],
      ];

      console.log(this.tweetsdata);
      this.screen_name = this.tweetsdata[0].user.screen_name;
      this.user = this.tweetsdata[0].user.name;
      this.profile_img_url = this.tweetsdata[0].user.profile_image_url_https;
      this.user_id = this.tweetsdata[0].user.id_str;
    });
  }
 }
}

tweets.component.html

<div class="twitter-container">
    <div class="twitter-carousel">
        <div class="twitter-header">
            <a class="tw-header" href="http://twitter.com/intent/user?user_id={{user_id}}" target="_blank">
                <img class="twitter-icon" src={{profile_img_url}}>
                <span>{{user}}</span>
                <span class="twitter-screen">@{{screen_name}}</span>
            </a>
        </div>

        <hr>

        <div class="tweet-container">
            <div *ngFor="let item of tweetsdata" class="tweets-card">
                <div class="tweet-text">
                    <p class="tweet-date">{{item.created_at | slice:0:10}}</p>
                    <p>{{item.text}}</p>
                    <!-- <div *ngIf="item.entities.media[0].media_url" class="tweet-img"> -->
                    <!-- <img [src]=item.entities.media[0].media_url/> --> <!-- either of these break the code if there is a tweet that doesn't contain an attached image -->
                    <div>


                        <p>{{getImage()}}</p>

                    </div>

                    <div class="interact-tweet">
                        <a href="https://twitter.com/intent/tweet?in_reply_to={{item.id_str}}" target="_blank"><i class="fa fa-reply" aria-hidden="true"></i></a>
                        <a href="https://twitter.com/intent/retweet?tweet_id={{item.id_str}}" target="_blank"><i class="fa fa-retweet" aria-hidden="true"></i></a>
                        <a href="https://twitter.com/intent/like?tweet_id={{item.id_str}}" target="_blank"><i class="fa fa-heart" aria-hidden="true"></i></a>
                    </div>
                </div>
            </div>
        </div>

    </div>

</div>

最佳答案

if (entities.media) // Code if it exists here
else // Code if it doesn't here

关于javascript - Angular4 - 如何检查 Twitter 媒体 key 是否存在或未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45995161/

相关文章:

Django 序列化为 JSON 错误 : 'MetaDict' object has no attribute 'concrete_model'

jquery - json数据中可以有group by吗?

javascript - Highcharts 十字准线标签在图例后面

javascript - 使用 JSONP,我有 'ReferenceError: data not defined'

angular - 在 Angular html 模板中整理属性顺序

javascript - Angular 2 HTTP 服务不返回 promise

angular - 将多个事件绑定(bind)到 Angular 2 中的元素

javascript - 有没有办法在 ChartJS 上默认显示工具提示(没有悬停饼图)

javascript - 在 Suitescript 中,我尝试使用 nlobjFilter 和日期时间变量按分钟过滤记录。有人有这方面的经验吗?

javascript - 仅在其他页面完全渲染后才从其他页面 AJAXing HTML