Search code examples
javascriptangulartypescriptrxjsrxjs-observables

Angular - Image appears while loading


I have a problem, I got an HTML element that acts like a loding spinner, and I would like it not to be displayed. I would to use the observables to be able to load that element only once the data is fully loaded. So far, in my component, i made it like that :

const matchTableList$ = this.matchTablesService.list().pipe(
            map(matchTables => {
                matchTables = matchTables.sort((a, b) => a.name.toLocaleLowerCase() === b.name.toLocaleLowerCase() ? 0 : a.name.toLocaleLowerCase() < b.name.toLocaleLowerCase() ? -1 : 1);
                this.matchTables$.next(matchTables);
            }),
            catchError( (error: HttpErrorResponse) => {
                this.loadingError$.next(true);
                return EMPTY;
            }),
            finalize(() => {
                this.prettyMessageData = new PrettyMessageContent();
                this.prettyMessageData.title = "hello"
                this.prettyMessageData.message = " ";
              this.prettyMessageData.withMessage(this.prettyMessageData.message);
            })
        );

and in my HTML i made :

<div *ngIf="!matchTablesLine" class="justify-content-center">
    <pretty-message style="width: 100%;" [data]="prettyMessageData">
    </pretty-message>
    <div class="d-flex justify-content-center mt-5">
        <button class="btn--primary" (click)="createMatchTable()"><i class="add-circle-line"></i>add</button>
    </div>
</div>

So the problem here is that, when there is no data, the pretty message is not displayed, and when there is data, the html div is loaded before i got the data, so it's weird to see a button while the page load. I think it is possible to use observables and operators here, but i really don't know which one to use to make this work. Thanks.

Edit : I solved the problem using a simple resolver, which is really helpful in that kind of cases.


Solution

  • I believe you are trying to delay the rendering of the button while the prettyMessageData is undefined. You can achieve this by adding a *ngIf=prettyMessageData on the button div.

     <div *ngIf="prettyMessageData" class="d-flex justify-content-center mt-5">
        <button class="btn--primary" (click)="createMatchTable()"><i class="add-circle-line"></i>add</button>
     </div>