angularfire2 - 获取标签数组

angularfire2 - getting an array of tags

我正在尝试获取一组标签以在我的模板中正确打印标签。我有这个:

<div *ngFor="let tweet of tweets | async">

    <p>
    {{ tweet.msg}}
    </p>
    <p>
    {{ tweet.username }}
    </p>
    Tags:
    <div *ngFor="let tag of tweet.tags">
        {{ tag }}
    </div>

</div>

由于索引原因,我的 firestore 数据库是这样的:

tweets: { 
  msg: "joe", 
  username: "bill2", 
  tags: {
    construction: true,
    computers: true
  }
}

除标签外,一切都正确打印。

我在想这样的事情,但后来我失败了。

this.tweetsCollection = this.afs.collection('tweets');
this.tweets = this.tweetsCollection.valueChanges();
this.tweets.subscribe(tags => {
  tags.forEach(tag => {
    Object.keys(tag).map(key => tag[key])
})

这显然行不通。那有必要吗?我觉得我想多了。

像这样的东西应该能满足您的需求:

  tweet_list = [];

  this.tweetsCollection = this.afs.collection('tweets');

  this.tweets = this.tweetsCollection.valueChanges();

  this.tweets.subscribe(tweet_collection => {

  tweet_collection.forEach(tweet => {

  let tweetElement = tweet;

  tweetElement.tags = Object.keys(tweetElement.tags);

  this.tweet_list.push(tweetElement);

});

});

您需要将 Firebase 返回的 'tags' 对象更改为一个数组,以便能够使用 *ngFor,这是通过这个位完成的:

Object.keys(tweetElement.tags);

问题是 tags 属性 是一个对象。 *ngFor需要数组循环,所以需要把tags属性转成数组

this.tweetsCollection = this.afs.collection('tweets');
this.tweets = this.tweetsCollection.valueChanges();
this.tweets.subscribe(arrayOfTweets => {
  arrayOfTweets.forEach(eachTweet => {
    // Ensure we don't get an undefined error if there is no 'tags' property on this tweet
    eachTweet['tags'] = eachTweet['tags'] ? eachTweet['tags'] : {}
    // Prepare HTML-friendly array of tags
    let arrayOfTags = [];
    // Loop over the 'tags' object's properties, we're interested in saving the name of the key of the property
    Object.keys(eachTweet['tags']).forEach(eachTagName => {
      arrayOfTags.push(eachTagName);
    })
    // Finally, overwrite the 'tags' property...
    eachTweet['tags'] = arrayOfTags;
  })
})

我想通了

this.tweetsCollection = this.afs.collection('tweets');
this.tweets = this.tweetsCollection.valueChanges()
  .pipe(
    tap(tweets => {

      tweets.forEach(tweet => {

        tweet['tags'] = tweet['tags'] ? tweet['tags'] : {}

        let tags = [];

        Object.keys(tweet['tags']).forEach(tag => {
          tags.push(tag);

        })

        tweet['tags_list'] = tags;
      })
    })
  )

有几件事。我无法覆盖 "tags" 数组,我不得不创建一个新数组:"tags_list"。此外,如果 angular < 5 中没有 do() 或 angular 6 中没有 pipe(tap()),您将无法在值更改后立即订阅。最后但同样重要的是,感谢 Jeremy W 和Troy Myers,我现在正确地抓住了钥匙。它还异步更新标签,这很棒。谢谢大家。