我有一项服务,以[url1,url2,...]等格式返回视频网址 因为这些是不安全的URL,所以在循环中消毒它们。
|-----------|------------|--------------------|----------------|
| uid | name | job | part |
|...........|............|....................|................|
| 1 | ab | tech, cs, perf | abcd, efgh |
| | | | |
在html中我写
import { Component, OnInit } from '@angular/core';
import { HomeService } from '../home/home.service'
import { BrowserModule, DomSanitizer } from '@angular/platform-browser'
import { SafeResourceUrl } from '@angular/platform-browser/src/security/dom_sanitization_service';
@Component({
selector: 'home',
templateUrl: './home.component.html'
})
export class HomeComponent implements OnInit {
videoCollection: string[] = [];
videoCollectionSafe: SafeResourceUrl[];
constructor(private homseService: HomeService, sanitizer: DomSanitizer) {
this.homseService.getVideos().subscribe((response) => this.videoCollection = response.json());
for (var i = 0; i < this.videoCollection.length; i++) {
this.videoCollectionSafe.push(sanitizer.bypassSecurityTrustResourceUrl(this.videoCollection[i]));
}
}
ngOnInit() {
}
}
这两行都不起作用。页面上没有显示任何内容。能不能帮助我解决这个问题。
答案 0 :(得分:1)
lesimoes部分正确,因为你应该使用生命周期钩而不是构造函数。
更大的问题是,在收到之前,您尝试在列表上进行迭代。 Observable Subscriptions是异步的,就像任何AJAX调用一样。因此,您必须在获取数据后对数据采取行动。简单地在AJAX调用之后放置代码行就不会这样做。
为此你有两个选择。
中这样做export class HomeComponent implements OnInit {
videoCollection: string[] = [];
videoCollectionSafe: SafeResourceUrl[] = [];
constructor(private homseService: HomeService, sanitizer: DomSanitizer) {}
ngOnInit() {
this.homseService.getVideos().subscribe(
response => this.videoCollection = response,
error => console.error(error),
() => this.videoCollection.forEach(video => this.videoCollectionSafe.push(sanitizer.bypassSecurityTrustResourceUrl(video)))
);
}
}
或onNext
处理程序中的“功能性”更多,因为您根本不需要中间videoCollection
成员,似乎:
export class HomeComponent implements OnInit {
videoCollectionSafe: SafeResourceUrl[] = [];
constructor(private homseService: HomeService, sanitizer: DomSanitizer) {}
ngOnInit() {
this.homseService.getVideos().subscribe(
videoCollection => videoCollection.forEach(video => this.videoCollectionSafe.push(sanitizer.bypassSecurityTrustResourceUrl(video)))
error => console.error(error)
);
}
}
另外,你还没有说明你正在使用哪种版本的角度,但是如果它在4.3之后你就不需要投射response.json()
because HttpClient
will do that for you。如果您运行的Angular版本太旧而您仍然拥有旧的Http
,那么您应该认真考虑升级,因为昨天发布了6.0.0。
答案 1 :(得分:-1)
将代码移至ngOnInit()。检查一下Angular生命周期:https://angular.io/guide/lifecycle-hooks
export class HomeComponent implements OnInit {
videoCollection: string[] = [];
videoCollectionSafe: SafeResourceUrl[];
constructor(private homseService: HomeService, sanitizer: DomSanitizer) { }
ngOnInit() {
this.homseService.getVideos().subscribe((response) =>
this.videoCollection = response.json());
for (var i = 0; i < this.videoCollection.length; i++) { this.videoCollectionSafe.push(sanitizer.bypassSecurityTrustResourceUrl(this.videoCollection[i]));
}
}
}