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



我构建的Web应用程序非常简单,并且使用了Angular 4和Firebase2。它列出了带有歌曲的表(标题,艺术家,< 3个图标和喜欢的数量(

我在壁炉上使用歌曲列表制作了一个对象/数组,每个对象都是上述3个属性的对象。我正在尝试做到这一点,以便当用户点击歌曲的核心时,喜欢的数量会增加一个,但是我尝试过的所有功能似乎都没有起作用。以下是我对此添加功能以及结果错误的尝试,在下面是我的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>

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

有关更多详细信息,请参见文档。

最新更新