簡體   English   中英

如何在角度2中制作“加載”屏幕

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM