在我的 Angular 应用程序中使用 api 调用值作为 div 的背景图片
Using an api call value as background image to a div in my Angular app
我正在创建一个电影搜索应用程序,需要使用图像作为 div 的背景。我从 api 调用中获得背景图片的 url。
我试过了
<div *ngFor="let movie of movies.results">
<div
class="thumbnail" style="background-image:
url(https://image.tmdb.org/t/p/w500{{movie.poster_path}})"
>
-- id: {{ movie.id }} -- name: {{ movie.title }}
</div>
</div>
这是我收到的警告
WARNING: sanitizing unsafe style value background-image: url(https://image.tmdb.org/t/p/w500/fw02ONlDhrYjTSZV8XO6hhU3ds3.jpg)
图像不显示。
然后我在其中一个值上尝试这个,看看它是否有效
this.sanitizer.bypassSecurityTrustUrl(`
https://image.tmdb.org/t/p/w500"${this.movies.results[0].poster_path}
`);
但我还是运行遇到了同样的问题??
然后我尝试了这个
background-image: [ngStyle]="{'background-image': 'url('+object.image+')'}"
仍然没有运气。
有人知道我该如何解决这个问题吗?## 标题 ##
看起来您非常熟悉使用 DomSanitizer 和 bypassSecurityTrustUrl
。我相信使用相同的方法,但使用 bypassSecurityTrustStyle
应该可以为您解决问题。
<div *ngFor="let movie of movies.results">
<div
class="thumbnail" [style.background-image]="getSafeStyle(movie.poster_path)"
>
-- id: {{ movie.id }} -- name: {{ movie.title }}
</div>
</div>
getSafeStyle(url: string) {
return this.sanitizer.bypassSecurityTrustStyle('url(\'' + url + '\')');
}
我正在创建一个电影搜索应用程序,需要使用图像作为 div 的背景。我从 api 调用中获得背景图片的 url。
我试过了
<div *ngFor="let movie of movies.results">
<div
class="thumbnail" style="background-image:
url(https://image.tmdb.org/t/p/w500{{movie.poster_path}})"
>
-- id: {{ movie.id }} -- name: {{ movie.title }}
</div>
</div>
这是我收到的警告
WARNING: sanitizing unsafe style value background-image: url(https://image.tmdb.org/t/p/w500/fw02ONlDhrYjTSZV8XO6hhU3ds3.jpg)
图像不显示。
然后我在其中一个值上尝试这个,看看它是否有效
this.sanitizer.bypassSecurityTrustUrl(`
https://image.tmdb.org/t/p/w500"${this.movies.results[0].poster_path}
`);
但我还是运行遇到了同样的问题??
然后我尝试了这个
background-image: [ngStyle]="{'background-image': 'url('+object.image+')'}"
仍然没有运气。
有人知道我该如何解决这个问题吗?## 标题 ##
看起来您非常熟悉使用 DomSanitizer 和 bypassSecurityTrustUrl
。我相信使用相同的方法,但使用 bypassSecurityTrustStyle
应该可以为您解决问题。
<div *ngFor="let movie of movies.results">
<div
class="thumbnail" [style.background-image]="getSafeStyle(movie.poster_path)"
>
-- id: {{ movie.id }} -- name: {{ movie.title }}
</div>
</div>
getSafeStyle(url: string) {
return this.sanitizer.bypassSecurityTrustStyle('url(\'' + url + '\')');
}