Angular 2 binding not updating after async operation

549 views Asked by At

In my Angular 2 app, I want to start by loading a number of SVGs, before starting the app proper. To do this, I first load a list of svg locations from the server, then fetch each one in turn.

I have a 'loading' property on my AppComponent thats controlling a couple of ngIfs to show/hide some Loading text. Problem is, once the svgs are all loaded, Angular doesn't update the binding in AppComponent.

Why is this? I thought zones took care of this?

The SvgLoader

import {Injectable, Output, EventEmitter, NgZone} from 'angular2/core';
import {Http, Response} from 'angular2/http';
import 'rxjs/Rx';
import {Observable} from 'rxjs/Observable';

const SVG_LIST:string = 'svg/list.json';

@Injectable()
export class SvgLoader {
    @Output() state: EventEmitter<string> = new EventEmitter();

    private svgs:{[file:string]:string};

    constructor(private http:Http){
        this.svgs = {};
    }

    getSvg(path:string):string {
        return this.svgs[path];
    }

    load():void {
        this.http.get(SVG_LIST)
            .map(res => {
                return <Array<string>> res.json().files;
            })
            .flatMap((files) => Observable.forkJoin(files.map(file => {
                return this.http.get('svg/' + file);
            })))
            .catch(this.handleError)
            .mergeAll()
            .subscribe(
                res => {
                    let index = res.url.indexOf('svg');
                    let path = res.url.substring(index);
                    this.svgs[path] = res.text();
                },
                error => console.error(error),
                () => {
                    this.state.emit('loaded');
                }
            );
    }

    private handleError(error:Response) {
        console.error(error);
        return Observable.throw(error.json().error || 'Server error');
    }
}

AppComponent

export class AppComponent {

    // On start, list the game sessions
    private state:string;
    public loading:boolean;

    constructor(private svgLoader:SvgLoader){
        this.loading = true;
        this.state = 'joining';
    }

    ngOnInit():void {
        this.svgLoader.state.subscribe(this.loaded);
        this.svgLoader.load();
    }

    loaded():void {
        console.log('loaded');
        this.loading = false;
    }
}

The template

<div>
    <h1 *ngIf="loading">Loading...</h1>


    <div *ngIf="!loading">
         Loaded
    </div>
</div>
0

There are 0 answers