alltej
alltej

Reputation: 7285

How to get the Object key of the associated object in angularFire2?

I query the database by userkey to find if an associated object exists:

let url = ``/userMember/${userKey}``;

const userMemberRef = this.af.database.object(url, { preserveSnapshot: true });

userMemberRef.subscribe(data => {
  if(data.val()!=null) {
    console.log(data.val());
    memberKey= data.val();
  }
});
return memberKey;

It logs this in console which is good because the data I want is there.

Object {-Ke2CyV2BJ5S3_7qcQj5: true}

But how can I return the child key value "-Ke2CyV2BJ5S3_7qcQj5"?

Seems to be very trivial. I appreciate your help!

Upvotes: 0

Views: 2375

Answers (2)

Sifeng
Sifeng

Reputation: 719

just use

const key = object['$key'];

Upvotes: 1

J. Adam Connor
J. Adam Connor

Reputation: 1734

data.val() actually references the value of userKey. Since userMember/${userKey} is not a path to a key value pair but an object, the "value" of userKey is that object. If you want to assign the key of a property of that object to a variable, you will need to map to the property's key.

Since it's safe to assume you can't predict what that key will be, there isn't a straightforward way to do this as far as I know. On the plus side there are a number of conceivable ways to do this. The important thing is that you understand the above.

The fact that you don't have a straightforward way to access this key and want to might be an indication that you should reconsider the structure of your model if at all possible.

I'll leave you with this example of how to "get at" the key, mostly to illustrate its relationship to the path you're using:

this.af.database.object(`userMember/${userKey}`)
.subscribe(member => console.log(Object.keys(member)[0]));

Upvotes: 1

Related Questions