我为了更新了一下你的代码工作:
@Component({
selector: 'my-app',
template: `
<div [style.background-image]="profileImage" style="width: 961px; height: 688px;"></div>
<h2> {{message}}</h2>
`,
})
export class App {
profileImage: string;
message: string;
constructor(private sanitizer: DomSanitizer) {
this.message = "Before async";
}
async ngOnInit() {
await delay(2000);
this.message = "Updating Photo";
const url = 'https://4.bp.blogspot.com/--RBVfn6FzOI/Tq5kOxFGKEI/AAAAAAAACnM/LaiZLD0sUKY/s1600/cats.jpg';
this.profileImage = this.sanitizer.bypassSecurityTrustStyle(`url(${url})`);
}
}
变化
1:变化:
constructor(sanitizer: DomSanitizer)
成这样:
constructor(private sanitizer: DomSanitizer)
因此具有sanitizer
作为类的一个成员,以便在ngOnInit()
访问。
2nd:设置<div>
的尺寸。这不会自动调整为您的背景图像大小。所以我设置了width
和height
。还有其他解决方案,例如使用图像的宽高比,或者保留不可见的<img>
。这些和更多描述在this answer。
3ND:因为你接收Plunker警告其在https
服务内容设置图像HTTP方案从http
到https
。
Updated Plunk
我不明白如何刷新使它的工作?它仍然在示例过程中。你能展示更多的代码和项目结构吗? – wannadream
在这个plunkr中工作正常https://plnkr.co/edit/jKMDoSEc8pq9BnhljiCw?p=preview –
plunkr正在为简单的情况工作,但是当从服务中检索数据时它不是 – jaks