【问题标题】:How to make a "loading" screen in angular 2如何在角度 2 中制作“加载”屏幕
【发布时间】:2017-01-09 11:38:04
【问题描述】:

下午好,我是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 中尝试过,但没有效果。

有人知道如何帮助我吗? 谢谢

【问题讨论】:

    标签: javascript angularjs angular


    【解决方案1】:

    您需要导入加载组件并将其设置为您需要使用它的组件的子组件,方法是将其包含在@Component 选择器的指令数组中。

    从 Angular 2 的角度来看,这很有意义,并且非常模块化。要使用它,请将其导入您的类并将其包含在指令数组中。然后,在模板中使用选择器。如果不导入,您将无法在任何地方使用选择器。

    【讨论】:

      【解决方案2】:

      作为 Bharat 所说的补充,您是否也将您的组件放入 app.module.ts 中?您应该将其包含在您的 @NgModule.declarations 中,然后将其包含在您要使用的组件中。

      【讨论】:

        【解决方案3】:

        您可以将加载器添加到应用程序的根组件中,并且只在根应用程序的模板中添加一次选择器。

        完成此操作后,您可以使用服务显示/隐藏加载组件。

        您的服务如下所示:

        @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;
                })
            }
        }
        

        您的根 html 模板:

        <loading [isRunning]="isRequesting"></loading>
        <router-outlet></router-outlet>
        

        现在您可以使用其他组件中的 LoaderService 隐藏/显示您的加载器,如下所示:

        //make loader visible
        loaderService.setIsRequesting(true);
        //make loader hide
        loaderService.setIsRequesting(false);
        

        例子:

        https://plnkr.co/edit/CYjDlLwmTRdYd7o5hMKS?p=info

        希望这会有所帮助。

        【讨论】:

        • 嗨,你有完整的例子吗?因为我做不到
        • 我添加了一个极简的例子。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-04-27
        • 2016-10-13
        • 2021-02-01
        • 1970-01-01
        • 2022-10-24
        相关资源
        最近更新 更多