无法使用 Angular 4 和 Firebase 2 执行真正简单的 Firebase 数据库更新

Can't perform Really Simple Firebase Database update using Angular 4 and Firebase 2

我正在构建的网络应用程序非常简单,并且使用 Angular 4 和 firebase2。它列出了 table 歌曲(标题、艺术家、<3 图标和喜欢的数量)

我用歌曲列表在 Firebase 上创建了一个 object/array,每一个都是具有上述 3 个属性的 object。我正在努力做到这一点,以便当用户点击歌曲的中心时,喜欢的次数会增加一个,但我尝试过的功能中 none 似乎有效。下面是我对这个 addLike 函数的尝试,以及产生的错误,下面是我的 html 模板、组件和数据结构的完整代码。任何帮助,将不胜感激。谢谢!

addLike(index){
this.songs.update(index, { likes: this.songs[index] + 1 });

} 

//(23,1): Supplied parameters do not match any signature of call target.

addLike(index){
this.songs[index].update({likes: this.songs[index] + 1 });
} 
//ERROR TypeError: Cannot read property 'update' of undefined

这是完整的代码

//COMPONENT HTML
<div> TEST </div>
<table class="table">
    <thead>
      <tr>
        <th>Title</th>
        <th>Artist</th>
        <th>Likes</th>
      </tr>
    </thead>
    <tbody>
  <tr *ngFor="let song of songs | async ; let i  = index">
<td>{{ song.title }}</td>
<td>{{ song.artist }}</td>
<td>{{ song.likes }}
 
            <i class="fa fa-heart-o" aria-hidden="true"  *ngIf="song.likes < 1"></i>
         <i class="fa fa-heart" aria-hidden="true" *ngIf="song.likes >= 1"></i>
<i class="fa fa-plus" aria-hidden="true" (click)="addLike(i)" ></i>

</td>
  </tr>
  </tbody>
  </table>

//COMPONENT TS

import { Component } from '@angular/core';
import { AngularFireDatabase, FirebaseListObservable, FirebaseObjectObservable } from 'angularfire2/database';
import { AngularFireAuthModule,AngularFireAuth} from 'angularfire2/auth';


@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})


export class AppComponent {
    title = 'Oxcord';


  songs: FirebaseObjectObservable<any>;
   constructor(db: AngularFireDatabase) {
    this.songs = db.object('/songs');
  }
  
  addLike(index){
this.songs[index].update({likes: this.songs[index] + 1 });

} 



}

{
  "songs" : [ {
    "artist" : "J Cole",
    "likes" : 3,
    "title" : "No Role Modelz"
  }, {
    "artist" : "Michael Jackson",
    "likes" : 8,
    "title" : "Thriller"
  }, {
    "artist" : "Meek Mill",
    "likes" : 0,
    "title" : "Trash"
  }, {
    "artist" : "Kendrick",
    "likes" : 6,
    "title" : "Humble"
  }, {
    "artist" : "Missy",
    "likes" : 4,
    "title" : "Work It"
  } ]
}

您正在更新本地 songs 属性。您应该改为更新数据库:

addLike(id: string, likes: number): void {
  this.db.object(`/songs/${id}`).update({ likes: likes + 1 });
}

这样,您可以在歌曲列表中调用 addLike 方法,传递歌曲 key 和当前的点赞数:

<i class="fa fa-plus" aria-hidden="true" (click)="addLike(song.$key, song.likes)" ></i>

然后,在您的方法中,您可以更新数据库中该歌曲位置的点赞数。

有关详细信息,请参阅 documentation