我正在使用 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)]
在查询上进行双向数据绑定(bind),然后单击一个使用 topbarcomponent.ts 中的函数 searchForm()
的按钮,该按钮通过服务获取我想要的结果。但是,如果我尝试循环访问 data.results (*ngFor="let video of data.results")
,则会收到 video is undefined
的错误。
我的模型是否不正确,我是否尝试错误地循环结果?如果您还没有注意到,我在这方面完全是初学者。
最佳答案
在 HTTP 请求完成之前,您的结果将不可用。在那之前它们将是未定义的。跳过未定义是行不通的:)
我建议您将其包装在 *ngIf 中,直到结果如下:
<mat-list *ngIf="data.results">
<mat-list-item *ngFor="let video of data.results"></mat-list-item>
<h3 matLine> {{ video.description }}</h3>
</mat-list>
您可以使用 *ngIf 显示一些替代内容,同时结果未定义
关于html - Angular 6,ngFor 标识符未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52681212/