用於進入組件前的加載動畫
第一步:index.html 定義動畫模板和樣式
// 樣式
<style type="text/css">.preloader {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
overflow: hidden;
background: #49a9ee;
z-index: 9999;
transition: opacity .65s
}
.preloader-hidden {
display: none
}
.cs-loader {
position: absolute;
top: 0;
left: 0;
height: 100%;
width: 100%
}
.cs-loader-inner {
transform: translateY(-50%);
top: 50%;
position: absolute;
width: 100%;
color: #fff;
text-align: center
}
.cs-loader-inner label {
font-size: 20px;
opacity: 0;
display: inline-block
}
@keyframes lol {
0% {
opacity: 0;
transform: translateX(-300px)
}
33% {
opacity: 1;
transform: translateX(0)
}
66% {
opacity: 1;
transform: translateX(0)
}
100% {
opacity: 0;
transform: translateX(300px)
}
}
.cs-loader-inner label:nth-child(6) {
animation: lol 2.5s infinite ease-in-out
}
.cs-loader-inner label:nth-child(5) {
animation: lol 2.5s .1s infinite ease-in-out
}
.cs-loader-inner label:nth-child(4) {
animation: lol 2.5s .2s infinite ease-in-out
}
.cs-loader-inner label:nth-child(3) {
animation: lol 2.5s .3s infinite ease-in-out
}
.cs-loader-inner label:nth-child(2) {
animation: lol 3.5s .4s infinite ease-in-out
}
.cs-loader-inner label:nth-child(1) {
animation: lol 2.5s .5s infinite ease-in-out
}
</style>
// 加載中DOM
<div class="preloader">
<div class="cs-loader">
<div class="cs-loader-inner">
<label> O </label>
<label> R </label>
<label> A </label>
<label> N </label>
<label> C </label>
<label> L </label>
<label> E </label>
</div>
</div>
</div>
第二步:路由守衛,在進入路由滿足條件時取消加載
- 請求登陸認證接口,已登錄 - 取消加載,進入路由;未登錄 - 跳轉至登錄頁,無需取消加載
export class GuardService implements CanActivate {
// 獲取加載元素
loadElem = document.querySelector('.preloader');
constructor(private _http: HttpClient) { }
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
// 構造參數
const encodeTrans = encodeURIComponent('http://192.155.1.32:4200/');
const params = new HttpParams().set('callback', encodeTrans);
// 登陸認證
return this._http.get('http://113.23.11.2:3120/isLogin', {params, withCredentials: true})
.map((data: any) => {
if ( data.errcode === 2001) { // 未登錄 - 重定向至登陸頁面
window.location.href = data.msg;
return false;
} else if ( data.errcode === 2000) { // 登錄成功 - 取消加載,進入路由
// 取消加載
const _loadThis = this;
setTimeout(function() {
if (_loadThis.loadElem) {
_loadThis.loadElem.className = 'preloader-hidden';
}
}, 100);
// 進入當前路由
return true;
}
});
}
}
加載效果預覽
