【发布时间】:2019-03-11 21:09:49
【问题描述】:
我正在使用 Google 的 youtube API,虽然我成功检索了数据,但我无法以有意义的方式显示它。我使用服务进行 API 调用,代码如下。我正在尝试显示从 API 获得的特定结果的列表,例如名称、描述和缩略图。
videos.service.ts
import {Injectable} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {Videolist} from '../Models/videolist.model';
@Injectable({
providedIn: 'root'
})
export class VideosService {
constructor(private http: HttpClient) {
}
public query: string;
results = new Array();
getVideos() {
const finalURL = 'https://www.googleapis.com/youtube/v3/search?key=*myapikey*&part=snippet' +
',id&order=date&maxResults=8&q=' + this.query;
return this.http.get<Videolist>(finalURL);
}
}
videolist.model.ts
import {Deserialize} from './deserialize.model';
export class Videolist implements Deserialize<Videolist> {
videoId: string;
description: string;
thumbnails: any;
deserialize(input: any): Videolist {
Object.assign(this, input);
return this;
}
}
topbar.component.ts
import {Component, OnInit} from '@angular/core';
import {VideosService} from '../services/videos.service';
import {ViewEncapsulation} from '@angular/core';
import {HttpClient} from '@angular/common/http';
@Component({
selector: 'app-topbar',
templateUrl: './topbar.component.html',
styleUrls: ['./topbar.component.css'],
encapsulation: ViewEncapsulation.None
})
export class TopbarComponent {
id = '2r5IbVJRvH4';
private player;
public ytEvent;
public token: string;
constructor(public data: VideosService) {
}
searchForm() {
this.data.getVideos().subscribe(data => {
this.data.results = data['items'];
console.log(this.data.results);
});
topbar.component.html
<div fxLayout="row" fxLayoutAlign="start center" class="margin">
<mat-toolbar>
<form class="example-form">
<mat-form-field class="testi">
<input id="haku" matInput placeholder="Search for songs" [(ngModel)]="data.query" name="query">
</mat-form-field>
<button (click)="searchForm()" mat-button style="margin-left: 40px !important;"><mat-icon matSuffix>search</mat-icon></button>
</form>
</mat-toolbar>
</div>
<div class="container" fxLayoutAlign="center center">
<div fxLayout="row" fxLayoutAlign="center start" class="keskii">
<mat-card class="vasen">
<mat-list>
<mat-list-item *ngFor="let video of data.results"></mat-list-item>
<h3 matLine> {{ video.description }}</h3>
</mat-list>
我在查询上使用[(ngModel)] 进行双向数据绑定,然后单击一个按钮,该按钮使用我的topbarcomponent.ts 中的函数searchForm(),它通过服务获得我想要的结果。但是如果我尝试循环通过data.results (*ngFor="let video of data.results"),我会得到video is undefined的错误。
我的模型是否不正确,我是否试图错误地循环遍历结果?如果您还没有注意到,那么在这方面我完全是初学者。
【问题讨论】:
-
您是否尝试过使用 ngIf 直到您的回复返回?
-
我有,但问题仍然存在。详细回复了其他回复
标签: html node.js angular typescript