Как прочитать свойство из Twitter API, используя Angular - PullRequest
0 голосов
/ 21 февраля 2020

Я создал очень простое c Angular приложение, в котором я просто получу свои статусы в Твиттере, используя Twitter API. Моя проблема связана с ответом JSON, который я получаю. Вот мой код:

twitter-timeline.component.ts

import { Component, OnInit } from '@angular/core';
import { TwitterserviceService } from '../twitterservice.service';

@Component({
  ...
})


export class TwitterTimelineComponent implements OnInit {

  myTimeline: any;

  constructor(private api: TwitterserviceService) { }

  ngOnInit() {
    this.getTwitterTimeline();
  }

  getTwitterTimeline(): void {
    this.api.getTimeline()
      .subscribe(
        myTimeline => {
          this.myTimeline = myTimeline;
          console.log(this.myTimeline);
        }
      )
   } 
}

Это ответ JSON, который я получаю:

{
  "statuses": [
    {
      "created_at": "Mon May 06 20:01:29 +0000 2019",
      "id": 1125490788736032770,
      "id_str": "1125490788736032770",
      "text": "Today's new update means that you can finally add Pizza Cat to your Retweet",
      "truncated": true,
      "entities": {
        "hashtags": [],
        "symbols": [],
        "user_mentions": [],
        "urls": [
          {
            "url": "https...some web link",
            "expanded_url": "https...twitter.com/i/web/status/11254907", <---------------THIS I WANT
            "display_url": "twitter.com/i/web/status/1…",
            "indices": [
              117,
              140
            ]
          }
        ]
      }, ...

В HTML я хочу прочитать это свойство, т.е. expanded_url и передать его в простой тег привязки, чтобы пользователь мог go перейти по этой ссылке.

twitter-timeline .component. html

<div class="container card" *ngFor="let tweets of myTimeline.data">
    <div class="row">
      <div class="col-sm-2 col-md-2 col-lg-2 image-column">
        <div class="twitter-logo-wrapper">
          <img class="twitter-logo" src="assets/images/icons/twitter-icon.png">
        </div>
      </div>
      <div class="col-sm-10 col-md-10 col-lg-10 text-column">
        <p class="screen-name">{{tweets.user.screen_name}}<br>
          <span class="user-status">{{tweets.user.description}}</span>
        </p>
      </div>
      </div>
      <div class="row">
        <div class="col-sm-12 col-md-12 col-lg-12">
          <span class="likes-count">{{tweets.user.followers_count}}</span>
          <span class="date-of-post">{{tweets.created_at}}</span>
          <span>
            <a href="{{tweets.urls.expanded_url}}" target="_blank">
              <button class="btn btn-info">Read</button>
            </a>
           </span>
         </div>
       </div>
     </div>

Но я получаю эту ошибку:

TwitterTimelineComponent...: ERROR TypeError: Cannot read property 'expanded_url' of undefined

Я также попытался добавить индекс в html как:

<div class="container card" *ngFor="let tweets of myTimeline.data; let i=index">

...

<a [attr.href]="tweets.urls[i].expanded_url" target="_blank">

1 Ответ

1 голос
/ 21 февраля 2020

Просто начните с expanded_url и так далее, и чтобы убедиться, что вы выбираете правильное свойство, используйте скобки ['']:

Пример: tweets['entities']['urls'][0]['expanded_url']

<a *ngIf="tweets['entities']['urls']?.length > 0" href="{{tweets['entities']['urls'][0]['expanded_url']}}" target="_blank">
   <button class="btn btn-info">Read</button>
</a>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...