Typescript variable inside function allocates information outside of it it is empty

Asked

Viewed 173 times

0

I need to take a variable within that function

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

but when access it out of 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
    });

  }
  • And this? this.db.collection<roomMembers>? This is not JS. It would be typescript?

2 answers

0

When Voce uses LET it is limiting its value to the scope where it was declared.

When Voce reuses the variable y = x[0]. id;, 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.

  • In addition to the scope problem, it looks like this function is asynchronous. If so, simply use var will not solve.

  • You better refactor

  • 1

    By the way, re-reading the code, there is no scope problem. It is always accessing within the scope.

  • he is doing an operation inside a function. There js is playing a new scope

  • No, because the statement was made out, the function accesses the outside variable. But there is more strange thing in this code, especially the part with Generics syntax, which does not exist in javascript

0


I think that function subscribe is asynchronous. This means that your alert from the outside executes before of you changing the value of y. You can only use y after having 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
        });
      }
    );
}

Browser other questions tagged

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