[英]How to make a “loading” screen in angular 2
下午好,我是angular
的初学者,我有以下疑问:
是否可以访问我所有组件中的选择器?
我把我的组件带到如下:
Import {DownloadComponent} from '../loading/carregando.component';
@Component({
Selector: 'app-questions',
TemplateUrl: './questions.component.html',
StyleUrls: ['./questions.component.css'],
EntryComponents: [LoadingComponent]
})
问题是,在我想要成本的任何html中我应该选择器
<loading [isRunning]="isRequesting"></loading>
我想把它放在一个地方,我尝试在index.html但它没有效果。
有谁知道如何帮助我? 谢谢
您需要导入加载组件并将其设置为需要使用它的组件的子组件,方法是将其包含在@Component选择器的指令数组中。
从角度2的角度来看这是有意义的,并且使其模块化很多。 要使用它,请在类中导入它并将其包含在directives数组中。 然后,在模板中使用选择器。 没有导入,您无法在任何地方使用选择器。
补充Bharat所说的,你是否也将你的组件放在app.module.ts
? 您应该将它包含在@NgModule.declarations
,然后将其包含在您要使用的组件中。
您可以将加载程序添加到应用程序的根组件,并在根应用程序的模板中仅添加一次选择器。
完成此操作后,您可以使用服务显示/隐藏加载组件。
您的服务看起来如下:
@Injectable()
export class LoaderService{
//BehaviorSubject takes an initial value false in this case and
//provides the most recent value where ever it has been subscribed to.
isRequesting: BehaviorSubject<boolean> = new BehaviorSubject(false);
public setIsRequesting (bool:boolean){
this.isRequesting.next(bool);
}
pubilc getIsRequesting: BehaviorSubject<boolean>{
return this.isRequesting;
}
}
在根组件中订阅BehaviorSubject,如下所示:
export class AppComponent{
isRequesting: boolean = false;
constructor(private loaderService: LoaderService)
ngOnInit(){
loaderService.getIsRequesting().subscribe(value=>{
this.isRequesting = value;
})
}
}
你的root html模板:
<loading [isRunning]="isRequesting"></loading>
<router-outlet></router-outlet>
现在,您可以使用其他组件中的LoaderService隐藏/显示您的加载程序,如下所示:
//make loader visible
loaderService.setIsRequesting(true);
//make loader hide
loaderService.setIsRequesting(false);
Exapmle:
https://plnkr.co/edit/CYjDlLwmTRdYd7o5hMKS?p=info
希望这可以帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.