Typescript variable within function allocates information out of it it is empty

0

I need to get a variable inside this function

    this.rooms.subscribe(
  function (x) {
      y= x[0].id;
      alert(y)
    });

but when it accesses it out of the function it returns to its initial value

here the whole code:

openChat(cid, nome) {
    let y = ''

    this.rooms = this.db.collection<roomMembers>
      ('room-members', ref => ref.where('uid', '==', this.uid).where('uidOutro', '==', cid)).valueChanges();

    this.rooms.subscribe(
      function (x) {
        y = x[0].id;
        alert(y)
      }
    );
    alert(y)

    this.navCtrl.push(Chat, {
      uid: cid,
      nome: nome,
      id: y
    });

  }
    
asked by anonymous 16.05.2018 / 22:33

2 answers

0

I think this subscribe function is asynchronous. That is to say that your% of out% executes before of you change the value of alert . You can only use y after you have assigned a value within the callback. That is, do so:

openChat(cid, nome) {
    let y = ''

    this.rooms = this.db.collection<roomMembers> // isso é typescript?
      ('room-members', ref => ref.where('uid', '==', this.uid).where('uidOutro', '==', cid)).valueChanges();

    let contexto = this;
    this.rooms.subscribe(
      function (x) {
        y = x[0].id;
        contexto.navCtrl.push(Chat, {
          uid: cid,
          nome: nome,
          id: y
        });
      }
    );
}
    
16.05.2018 / 23:59
0

When you use LET you are limiting the value of it to the scope where it was declared.

When you reuse the variable y = x [0] .id; , you put this new value of y in a new scope.

To solve your problem use VAR instead of LET, or refactor the code, so that the value is returned.

    
16.05.2018 / 23:39