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

Discussão em 'Angular' iniciado por dKab, Setembro 10, 2025.

  1. dKab

    dKab Guest

    I have a service which 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 asynchronously, 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.

    Continue reading...

Compartilhe esta Página