Angular 2-预加载背景图片? [英] Angular 2 - Preload background image?

查看:216
本文介绍了Angular 2-预加载背景图片?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个有角度的项目,其中有一个大的背景图像填充页面,一个简单的侧边栏带有链接,单击该链接时,将使用另一个图像(来自CDN)更改背景的url.由于这些图像很大,因此它们需要一两秒才能加载,而且很明显,因此我想添加一个预加载器,但是我不确定在角度2中如何实现.

I have this angular project where I have a big background image that fills the page and a simple sidebar with links that when clicked, will change the url of the background with another image (from a cdn). Since these images are fairly big they take a second or two to load and it's noticeable, I want to add a preloader but I'm not sure how that would be done in angular 2.

在我的html中,我有这个:

In my html I have this:

<section class="fullsizebg image-bg" [ngStyle]="{'background-image': 'url(' + urlImage + ')'}"></section>

在组件的构造函数中填充了urlImage变量,并且侧栏链接使用如下简单函数更改了单击时的值:

The variable urlImage is populated in the constructor of the component and the sidebar links changes the value of it on click with a simple function like so:

generateImage(data: any){
    this.urlImage = 'http://example.com/mycdn/'+this.data.url+'.jpg';
}

因此,实际上url会立即更改,但是图像加载需要一些时间.我想添加一个加载gif或类似的东西,以使图像平滑地呈现给用户,而不像现在这样跳动.

So the url is in fact changed instantly but the image takes a bit to load. I'd like to add a loading gif or something like that to keep the image change smooth to the user and not jumpy like it is now.

推荐答案

一种方法是使用Blob获取图像并将其存储在img组件中,这样您就可以动手了加载过程中,您可以添加加载gif:

One way to do it would be to use Blob to get the image and store it in an img component, this way you have your hands on the loading process and you can add your loading gif:

@Component({
   selector:'loading-image',
   template:'<img alt="foo" [src]="src"/>'
})
export class ExampleLoadingImage{

   public src:string = "http://example.com/yourInitialImage.png";

   constructor(private http:Http){}

   generateImage(data: any): void {
      this.src = 'http://www.downgraf.com/wp-content/uploads/2014/09/01-progress.gif'; //Just a random loading gif found on google.
      this.http.get('http://example.com/mycdn/'+this.data.url+'.jpg')
         .subscribe(response => {
            let urlCreator = window.URL;
            this.src = urlCreator.createObjectURL(response.blob());
         });
    }
}

NB :您应该键入数据参数,键入是确保代码一致性的好方法,any仅应用作小丑,例如Java中的Object

N.B: You should type your data parameter, typing is a good way to ensure consistency over your code, any should only be used as a joker, like Object in Java.

这篇关于Angular 2-预加载背景图片?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆