调用API服务后,模板中有一个未定义的变量,但在控制台中看到了预期的结果。
我的VideoComponent调用了API
export class VideoComponent implements OnInit {
video: Video = new Video();
constructor(private apiService: ApiService, private route: ActivatedRoute) {
}
ngOnInit() {
this.route.params.subscribe(params => {
this.apiService.getOneVideoByID(params['id']).subscribe((video: Video) => {
this.video = video;
console.log(this.video);
});
});
}
}
有我的API服务:
export class ApiService {
PHP_API_SERVER = 'http://127.0.0.1/TutoWorld/backend/api';
private headers;
constructor(private httpClient: HttpClient) {
this.headers = new HttpHeaders().set('Content-Type', 'application/json')
}
getOneVideoByID(id: number): Observable<Video> {
return this.httpClient.get<Video>(`${this.PHP_API_SERVER}/readOne?id=${id}`,{headers: this.headers});
}
}
我的模板:
<div class="block5"></div>
<div id="videoContainer">
<p>video title: {{video.titre}} </p>
</div>
还有我的视频模型:
export class Video {
id: number;
url: string;
titre: string;
langue: string;
description: string;
date_creation: string;
date_ajout: string;
auteur_id: number;
auteur_nom: string;
}
如果有人可以帮助我解决此问题,那就太好了。
谢谢
答案 0 :(得分:1)
看着控制台,它似乎是一个数组。
我也将避免嵌套订阅,请尝试以下操作:
import { switchMap } from 'rxjs/operators'; // this import could be wrong, double check
.....
ngOnInit() {
this.route.params.pipe(
switchMap(params => this.apiService.getOneVideoByID(params['id'])),
).subscribe((video: Video) => {
this.video = video[0];
console.log(this.video);
});
}
答案 1 :(得分:0)
谢谢,它可以正常工作,但是我在html中有一个,现在又收到另一个错误消息:https://zupimages.net/up/20/09/cik2.png
有我的iframe代码:
<iframe width="1280" height="720"
src="https://www.youtube.com/embed/{{getVideoID(video.url) | safe}}"
frameborder="0"
allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture"
allowfullscreen>
</iframe>
和我的GetVideoID代码:
getVideoID(url: string) {
return this.apiService.youtube_parser(url);
}
youtube_parser(url) {
let regExp = /^.*((youtu.be\/)|(v\/)|(\/u\/\w\/)|(embed\/)|(watch\?))\??v?=?([^#\&\?]*).*/;
let match = url.match(regExp);
return (match && match[7].length == 11) ? match[7] : false;
}
管道代码也是如此:
import {Pipe, PipeTransform, SecurityContext} from '@angular/core';
import {DomSanitizer} from '@angular/platform-browser';
@Pipe({
name: 'safe'
})
export class SafePipe implements PipeTransform {
constructor(private sanitizer: DomSanitizer) { }
transform(url) {
return this.sanitizer.sanitize(SecurityContext.URL, url)
}
}
答案 2 :(得分:0)
要在此处回答初始问题,我必须说您将来自数组的API的响应视为单个实例。这就是为什么您未定义它的原因:)