角度 2 修复动态粒子 JS 无法读取 null 的属性'getElementsByClassName'



我正在使用angular 2 v4开发一个web应用程序,我想使用一个参数动态地包含不同的Particles.js,我想加载一个特定的粒子格式。

问题是这个参数来自数据库,我通过可观察性来管理它,因此不可能从ngOnInit函数或构造函数加载它。

一切都很好,并且正确加载了文档,问题是当我离开该路线时,会出现错误:

Cannot read property 'getElementsByClassName' of null

这里我有一些我的配置

angular cli.json

"scripts": [
...
"../node_modules/particles.js/particles.js",
...
],

登录.ts

declare var particlesJS: any;
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.scss']
})
export class LoginComponent implements OnInit {
// Color variables----------------------------------------------------
default = false;
amber = false;
green = false;
red = false;
blue = false;
gray = false;
white = false;
purple = false;
orange = false;
lightBlue = false;
// Color variables----------------------------------------------------
clientConfig: any;
constructor(public clientConfigService: ClientConfigService) {
this.clientConfigService.readData().subscribe(data => {
this.clientConfig = data;
this.changeTheme(this.clientConfig);
} );
}
ngOnInit() {}
changeTheme(config: Client) {
this.default = false;
this.amber = false;
this.green = false;
this.red = false;
this.blue = false;
this.gray = false;
this.white = false;
this.purple = false;
this.orange = false;
this.lightBlue = false;
switch (config.color) {
case 'default': this.default = true; particlesJS.load('particles-js', 'assets/data/default-particles.json'); break;
case 'amber': this.amber = true; particlesJS.load('particles-js', 'assets/data/amber-particles.json'); break;
case 'green': this.green = true; particlesJS.load('particles-js', 'assets/data/green-particles.json'); break;
case 'red': this.red = true; particlesJS.load('particles-js', 'assets/data/red-particles.json'); break;
case 'blue': this.blue = true; particlesJS.load('particles-js', 'assets/data/blue-particles.json'); break;
case 'gray': this.gray = true; particlesJS.load('particles-js', 'assets/data/gray-particles.json'); break;
case 'white': this.white = true; particlesJS.load('particles-js', 'assets/data/white-particles.json'); break;
case 'purple': this.purple = true; particlesJS.load('particles-js', 'assets/data/purple-particles.json'); break;
case 'orange': this.orange = true; particlesJS.load('particles-js', 'assets/data/orange-particles.json'); break;
case 'lightblue': this.lightBlue = true; particlesJS.load('particles-js', 'assets/data/light-blue-particles.json'); break;
default: this.default = true; particlesJS.load('particles-js', 'assets/data/default-particles.json'); break;
}
}
}

login.html

<div id="particles-js"></div>

该路由属于"localhost:4200/login">,此时一切正常,控制台中没有错误。问题是当我转到另一条路由时,例如"localhost:420/forget"(或任何其他(。就在我转到其他路线时,控制台中出现此错误:

ERROR TypeError: Cannot read property 'getElementsByClassName' of null
at window.particlesJS (scripts.bundle.js:4114)
at XMLHttpRequest.xhr.onreadystatechange (scripts.bundle.js:4150)
at ZoneDelegate.webpackJsonp.../../../../zone.js/dist/zone.js.ZoneDelegate.invoke (zone.js:391)
at Object.onInvoke (core.es5.js:3890)
at ZoneDelegate.webpackJsonp.../../../../zone.js/dist/zone.js.ZoneDelegate.invoke (zone.js:390)
at Zone.webpackJsonp.../../../../zone.js/dist/zone.js.Zone.runGuarded (zone.js:161)
at XMLHttpRequest.<anonymous> (zone.js:144)



更新

这是我所有的HTML代码,包括路由。此页面显示在路线中http://localhost:4200/session/signin

因此,当我点击登录按钮并转到任何其他路线时(在这种情况下http://localhost:4200/dashboard)基础部件被破坏了。。。控制台显示错误

路由

export const AppRoutes: Routes = [
{
path: '', component: AdminLayoutComponent,
canActivate: [AuthGuard], children: [{ path: 'dashboard',  loadChildren: './dashboard/dashboard.module#DashboardModule' }]
},
{
path: '',
component: AuthLayoutComponent,
children: [{
path: 'session',
loadChildren: './session/session.module#SessionModule'
}]
}];

登录.html

<div class="whitemask">
<div id="particles-js" fxLayout="column" fxLayoutAlign="center center" class=" gradient-animated">
<div class="session-wrapper" style="position: absolute;">
<div class="mat-card-login">
<div class="login-form">
<form [formGroup]="form" (ngSubmit)="onSubmit()" autocomplete="off">
<div fxLayout="column" fxLayoutAlign="space-around">
<div class="pb-1">
<mat-form-field color="accent" class="login-input" style="width: 100%">
<input name="i-sl-li-lg-001" matInput placeholder="Cuenta"  [formControl]="form.controls['account']">
<mat-error *ngIf="form.controls['account'].hasError('required') && form.controls['account'].touched" class="mat-text-warn">Debe ingresar una cuenta válida.</mat-error>
</mat-form-field>
</div>
<div class="pb-1">
<mat-form-field color="accent" class="login-input" style="width: 100%">
<input name="i-sl-li-lg-003" matInput color="accent" [type]="passvisible" placeholder="Contraseña" [formControl]="form.controls['password']">
<mat-icon matSuffix (click)="visibePass()" style="cursor: pointer" [ngStyle]="{ 'color': passvisible === 'password' ? 'rgba(0,0,0,0.44)' : 'black' }">visibility</mat-icon>
<mat-error *ngIf="form.controls['password'].hasError('required') && form.controls['password'].touched" class="mat-text-warn">Debe ingresar una contraseña.</mat-error>
</mat-form-field>
</div>
<div *ngIf="showMessage" fxLayout="row" fxLayoutAlign="center center" class="errortext" style="margin-bottom: 10px; margin-top: -15px">{{ error }}</div>
<button id="b152" mat-raised-button class="login-button" type="submit" [disabled]="!form.valid">Iniciar sesión</button>
<div style="padding-top: 10px" fxLayout="row" fxLayoutAlign="center center">
<a class="forgot" [routerLink]="['/session/forgot']">¿Olvidaste tu contraseña?</a>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>

登录.ts提交时的功能

onSubmit() {
this.authService.login(this.form.controls['account'].value,
this.form.controls['password'].value).subscribe(
data => {
if (data.access_token) {
this.router.navigate(['/dashboard']);
this.showMessage = false;
} else {
if (data.status) {
switch (data.status) {
case '401': this.error = 'Error'; break;
case '402': this.error = 'User nor found'; break;
}
}
}
},
error => {
this.error = 'Login Error, try it later.';
});
}

通过将构造中的代码移动到ngAfterViewInit重试。

declare var particlesJS: any;
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.scss']
})
export class LoginComponent implements OnInit, AfterViewInit {
// Color variables----------------------------------------------------
default = false;
amber = false;
green = false;
red = false;
blue = false;
gray = false;
white = false;
purple = false;
orange = false;
lightBlue = false;
// Color variables----------------------------------------------------
clientConfig: any;
constructor(public clientConfigService: ClientConfigService) {
}
ngOnInit() {}
ngAfterViewInit() {
this.clientConfigService.readData().subscribe(data => {
this.clientConfig = data;
this.changeTheme(this.clientConfig);
} );
}
changeTheme(config: Client) {
this.default = false;
this.amber = false;
this.green = false;
this.red = false;
this.blue = false;
this.gray = false;
this.white = false;
this.purple = false;
this.orange = false;
this.lightBlue = false;
switch (config.color) {
case 'default': this.default = true; particlesJS.load('particles-js', 'assets/data/default-particles.json'); break;
case 'amber': this.amber = true; particlesJS.load('particles-js', 'assets/data/amber-particles.json'); break;
case 'green': this.green = true; particlesJS.load('particles-js', 'assets/data/green-particles.json'); break;
case 'red': this.red = true; particlesJS.load('particles-js', 'assets/data/red-particles.json'); break;
case 'blue': this.blue = true; particlesJS.load('particles-js', 'assets/data/blue-particles.json'); break;
case 'gray': this.gray = true; particlesJS.load('particles-js', 'assets/data/gray-particles.json'); break;
case 'white': this.white = true; particlesJS.load('particles-js', 'assets/data/white-particles.json'); break;
case 'purple': this.purple = true; particlesJS.load('particles-js', 'assets/data/purple-particles.json'); break;
case 'orange': this.orange = true; particlesJS.load('particles-js', 'assets/data/orange-particles.json'); break;
case 'lightblue': this.lightBlue = true; particlesJS.load('particles-js', 'assets/data/light-blue-particles.json'); break;
default: this.default = true; particlesJS.load('particles-js', 'assets/data/default-particles.json'); break;
}
}
}

您收到此错误是因为particles.js试图访问的html元素尚未生成。有关详细信息,请查看此文档。

最新更新