I cannot print object attribute in log

Asked

Viewed 248 times

1

Well, I have a class:

export class Usuario{


private id : string;
private bluetoothMAC: string;
private cpf: string;
private nome: string;
private oficinaVisitadas: Oficina[];
private cacheMAC: Mac[];
private saidaMAC: Mac[];

constructor(){

}
//gets and sets

I have this method that returns the user

getUserKeyMAC(MAC: string):Usuario{
let key: string = ""
let oMAC: string = ""
let rt: any;
let us:any;
oMAC = MAC
this.items = this.angularFire.list('/Usuarios', { preserveSnapshot: true });
us = new Usuario
this.items.subscribe(snapshots => {
  snapshots.forEach(snapshot => {
    let arrayTemp:any
    let aMAC: string = ""
    aMAC = snapshot.val().bluetoothMAC
    if (aMAC === oMAC) {
      us.$id=snapshot.key
      us.$nome = snapshot.val().nome;
      us.$cpf = snapshot.val().cpf;
      us.$bluetoothMAC = snapshot.val().bluetoothMAC;
      arrayTemp= new Array;
      arrayTemp = snapshot.val().oficinaVisitadas
      us.$oficinaVisitadas=arrayTemp
    }
  });
})
return us
}

and here where I get the return,try to print any user attribute,but it comes as Undefined:

marcaEntrada(obs:Observable<Mac[]>){
obs.subscribe(macs=>{
  macs.forEach((mac)=>{
      let us:any;
      us = new Usuario;
      us=this.hfb.getUserKeyMAC(String(mac.mac));
      console.log(us.$id); 
  })
  })
  }

this and the exit: log

but if I try to print the whole object it appears normally:

Objeto todo

2 answers

1


The problem is that you are waiting for the return that is not yet ready. Your getUserKeyMAC function will not be able to pass the return you expect at the desired time, as it is asynchronous. This means that the lines below will be processed without any waiting for the other:

this.items = this.angularFire.list('/Usuarios', { preserveSnapshot: true });
us = new Usuario
this.items.subscribe(snapshots => {// códigos aqui});
return us;

With Angular and this new asynchronous call architecture you will have to change your thinking a little bit whenever you make an HTTP connection or something that returns an Observable, Subscribe, etc. So, never expect a return at the time of the call.

See a concept of how you could adapt.

getUserKeyMAC(MAC: string): Observable<Usuario[]>{

  // outras coisas aqui 

   this.items = this.angularFire.list('/Usuarios', { preserveSnapshot: true });

   return this.items.map(snapshot => {

    let us = new Usuario();
    let arrayTemp:any
    let aMAC: string = ""
    aMAC = snapshot.val().bluetoothMAC
    if (aMAC === oMAC) {
      us.$id=snapshot.key
      us.$nome = snapshot.val().nome;
      us.$cpf = snapshot.val().cpf;
      us.$bluetoothMAC = snapshot.val().bluetoothMAC;
      arrayTemp= new Array;
      arrayTemp = snapshot.val().oficinaVisitadas
      us.$oficinaVisitadas=arrayTemp
    }

     return us
  });
})

}

mark Center(Obs:Observable){

// The method call would look like this

obs.subscribe(macs => {
  macs.forEach((mac) => {

      let us:any;
      us = new Usuario;
      let resultObservable =this.hfb.getUserKeyMAC(String(mac.mac));
      resultObservable.subscribe(usuarios => {

             if (usuarios.lenght > 0) 
             { 
             }
       }, (error)=> { console.log('ocorreu um erro', error); });
   }
}

I won’t say it’s simple, it’s not simple, I took a while to get the idea, but you’ll need to adapt to these types of calls.

And the question on the air is, why did printing the object on the.log console work? My theory is this, you printed an object while the call was active and, as it is an object, the properties could be very well altered throughout the processing, and that’s exactly what happened. To prove this theory, instead of using console.log(us), you can use console.log(JSON.stringify(us)). This will show you that the object is empty.

If you need help to adapt, post here, or create an example in the plunker, then it is easier to assist.

  • I got it,I was trying to avoid using the Observable after setting the user, as I will do various validations and updates within firebase based on the returned user,the basics of this angular module and insert the schedule in which the mac was captured and update until last seen,this will require a lot of code within the subscribe,sera it has problem?

  • I don’t see any problems, but I suggest you, instead of putting all the code inside the subscribe, call the method inside the subscribe. This way the code becomes more readable. Example: observable.subscribe(us=> this.trataUsuario(us));

  • But in this case the object would be populated or controlled by the observable still?

  • It would already be the populated object. But in this situation it would be equal to the example code that I posted last (the resultObservable.subscribe), which is when the object is already outside observable

  • Typeerror: resultObservable.subscribe is not a Function

  • The use of the suggested instruction will depend greatly on the object contained in this.items. Therefore, the ideial to assist you would be to create a case in the plunker. If you are using angular lib/angularfire2 the type of items will be items: Firebaselistobservable<any[]>, as in the home page example. Perhaps, some rxjs package such as Observable, Operator, Subscriber or Subscription is missing. The safest is for you to investigate (console.log) what type of items and methods it contains. Package import: import { <pack_nm> } from 'rxjs/<pack_nm>';.

Show 1 more comment

0

Hello, good afternoon.

You tried to use it that way?

Class


export class Usuario{
    private _id : string;
    private _bluetoothMAC: string;
    private _cpf: string;

//gets and sets

get id():string {

    return this._id;

}

set id (id:string) {

    this._id = id

}

Function that arrow the attributes


us = new Usuario;
us.cpf = "000.000.000.00";
us.id = "13449483890";
us.bluetoothMAC = "...";

Class User log console



console.log(us.id);

  • already yes, it works,

Browser other questions tagged

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