How to delay instantiation until data from a service is retrieved in Angular 2?

I have a service that retrieves data from a server using a method get:

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 that 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;
        });
}

Since the data is retrieved asynchronously, the component is created and visualized, and only after receiving this data. The view is populated with data and ultimately looks good, but first I have an error in the console:

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

This happens in my opinion:

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

I want the component to wait until the data is received before it is displayed on its own. Is it possible? I was thinking about life-cycle bindings , but the documentation is so poor that I cannot understand it.

+4
1

- ngIf.

- ...

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

, user.avatar .

+2

Source: https://habr.com/ru/post/1624066/


All Articles