Use variable received via route angle 2 final releasee

0

I'm starting to learn angle 2 and am having a question about how to use variable within a component ( AppComponent.ts ), received via service. I've sent via the id of a register and I get the distinguished component, so much I can see it in the view through interpolation {{}}. But I'd like to use this variable, which is an object, to put another variable in this component, and I'm not getting it, the value stays as undefined. In the Component I get the following variable:

import.....

    export clas.....{
     id : number;
     aaa : string;

ngOnInit() {

        this.id = +this.route.snapshot.params['id'];
        this.usuario = new Usuario();
        this.usuariosService.buscarPorId(this.id)
            .subscribe(
                    usuario => {
                    this.usuario = usuario
                  });

    this.aaa = this.usuario['nome'];
    this.log('ngOnInit');
    console.log(this.aaa);
}    

The value of the aaa variable is not assigned, I already tried it in several ways, I already searched the net, but I can not use what I get for route inside the TS file, only inside HTML. >     

asked by anonymous 01.11.2016 / 19:12

1 answer

0

Hello,

The problem is related to the http call being asynchronous, and when I throw:

this.aaa = this.usuario['nome'];

runs, has not yet returned from server. For the correct operation you should work with Observer or Promise, follow an example, using promise:

this.http.get('http://test.com/api/user') .map(res => res.json()).toPromise().then((result) => {
                this.usuario = usuario;
                this.aaa = this.usuario['nome'];
            }).catch(() => {
               console.log('Error')
            });
    
16.11.2016 / 21:19