Search code examples
angulartypescriptweb-component

How to delay component instantiation until data from service is received in Angular 2?


I have a service wich fetches data from server with its get method:

export class UserService implements IRestService<User> {
    constructor(public http: Http) {
    }

    get(): Rx.Observable<User> {
        return this.http.get('api/ui_user', <any> {
            headers: {'Accept': 'application/json'}
            })
            .toRx()
            .map(res => res.json());
    }

And I have a component which uses this service.

constructor(emplService: EmployeesService, userService: UserService){
    this.emplService = emplService;
    this.isDisplayMenu = false;
    this.user = new User();

    userService.get()
        .subscribe(usr => {
            this.user = usr;
        });
}

Because data is fetched asyncronously, the component is instantiated and rendered, and only after that data is received. View gets populated with data and looks good eventually but at first I have an error in console:

GET data:image/png;base64,undefined net::ERR_INVALID_URL

It happens in my view:

 <img class="user-avatar" [src]="'data:image/png;base64,' + user.avatar">

I want the component to wait until data is received before it rendered itself. Is this possible? I was thinking about lifecycle hooks but documentation is so poor I can't understand it.


Solution

  • One way would be to use the ngIf directive.

    Something like...

    <img *ngIf="user.avatar" class="user-avatar" [src]="'data:image/png;base64,' + user.avatar">
    

    Then the element won't then be rendered in the page until the user.avatar is truthy.