api请求未显示结果* ngFor * ngIf

时间:2019-02-10 16:50:18

标签: html angular typescript api

我需要显示正在获取的数据,但没有显示,我尝试了ngIf和ngFor

我使用的是角度6,并试图在HTML中显示电影中的数据,但是数据似乎是空的,我尝试了很多解决方案,但似乎都没有用。

<app-logo></app-logo>
<app-options></app-options>
<div style="display:none;" id="root"></div> 
<div class="col s6"> 
  <button routerLink="/halfhour" (click)=searchData() class="options" id="menos-30-min" value="25 min">Menos de 30 min</button>
</div>
<div *ngIf="data?.data">
<ng-container *ngFor="let data of data">
  
  <div class="row">
    <div class="col s5">
    <img class="backgrounds" src="{{data?.Poster}}">
    <div class="background" style="background-image: url({{data?.Poster}}); background-size: cover; background-position: center center; background-repeat: no-repeat; background-attachment: fixed; height:300px; width: 100%;"></div>
    </div>
    <div class="col s7">
    <div class="information">
    <p class="title">Title: {{data?.Title}}</p>
    <p class="runtime">Runtime: {{data?.Runtime}}</p>
    <p class="other-data">Year: {{data?.Year}}</p>
    <p class="other-data"> Genre: {{data?.Genre}}</p>  
    <p class="resumen"> Plot: {{data?.Plot}}</p>
    <p class="other-data"> Tipo: {{data?.Type}}</p>
    </div>
    </div>
  </div>
</ng-container>
  </div>
    <h1>{{id}}</h1>

@Component({
  selector: 'app-half-hour',
  templateUrl: './half-hour.component.html',
  styleUrls: ['./half-hour.component.css']
})
export class HalfHourComponent implements OnInit {

  constructor(private http: Http) {
  }
  data: any [];
  id;
  getRandom() {
    const omdbData = ['0386676', '1865718', '0098904', '4508902', '0460649', '2861424', '0108778', '1305826', '0096697', '0149460'];
    const randomItem = omdbData[Math.floor(Math.random() * omdbData.length - 1) + 1];
    return this.id =  randomItem;
  }

  searchData() {
    this.getRandom();
    this.http
      .get('https://cors-anywhere.herokuapp.com/http://www.omdbapi.com/?i=tt' + this.id + '&apikey=')
      .pipe(map((res: Response) => res.json()))
      .subscribe(data => {
        this.data = Array.of(this.data);
        console.log(data);
        console.log(this.id);
      });
    }
  ngOnInit() {
  }

}

数据的属性显示为空。

1 个答案:

答案 0 :(得分:2)

HTTP请求调用应添加到ngOninit()内。这是更新的代码

ngOnInit(){
  this.data = [];

    this.getRandom();
    this.http
      .get('https://cors-anywhere.herokuapp.com/http://www.omdbapi.com/?i=tt' + this.id + '&apikey=')
      .pipe(map((res: Response) => res.json()))
      .subscribe(data => {
        this.data = (data) ? data.slice() : [];
        console.log(data);
        console.log(this.id);
      });
}