Use received variable via angular route 2 final releasee

Asked

Viewed 52 times

0

I’m starting to learn angular 2 and I’m having a question of how to use variable within a component (AppComponent.ts), received via service. I sent via served the id of a register and get in the distinct component, so much so that I can visualize it in the view through interpolation {{ }}. But I would like to use this variable, which is an object, to mount another variable in this component, and I’m not getting it, the value is as undefined. In the Component I get the variable with follows:

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 variable aaa is not assigned, I have tried several ways, I have searched the net, but I can not use what I receive by route within the TS file, only within the HTML.

  • I believe this.usuario.name if the name inside the object is public if private creates a public getter method by getting this.usuario.getName(), puts the service code and this user object what are its properties/methods?

1 answer

0

Hello,

The problem is related to http calling being asynchronous, and when chunk :

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

is executed, has not yet returned from server. For the correct functioning Voce must 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')
            });

Browser other questions tagged

You are not signed in. Login or sign up in order to post.