您将需要创建一个可以存储对加载组件的引用的加载服务。然后将该加载服务注入需要能够切换该加载组件的其他组件的构造函数中。
import { Injectable } from '@angular/core';
import { LoadingComponent } from './loading.component';
@Injectable()
export class LoadingService {
private instances: {[key: string]: LoadingComponent} = {};
public registerInstance(name: string, instance: LoadingComponent) {
this.instances[name] = instance;
}
public removeInstance(name: string, instance: LoadingComponent) {
if (this.instances[name] === instance) {
delete this.instances[name];
}
}
public hide(name: string) {
this.instances[name].hide();
}
public show(name: string) {
this.instances[name].show();
}
}
一定要LoadingService
在你的模块providers
数组中注册你的!
然后在LoadingComponent
你可以注入LoadingService
,以便LoadingComponent
可以向LoadingService
它注册自己,它应该向该服务注册自己:
import { Component, OnInit, Input, OnDestroy } from '@angular/core';
import { LoadingService } from './loading.service';
@Component({
selector: 'yourapp-loading',
templateUrl: './loading.component.html',
styleUrls: ['./loading.component.scss']
})
export class LoadingComponent implements OnInit, OnDestroy {
@Input() name: string;
private isVisible = false;
constructor(private service: LoadingService) {}
ngOnInit() {
if (this.name) {
this.service.registerInstance(this.name, this);
}
}
ngOnDestroy() {
if (this.name) {
this.service.removeInstance(this.name, this);
}
}
/* ... code to show/hide this component */
}