【问题标题】:How do I implement delete operation using AngularFireStore如何使用 AngularFireStore 实现删除操作
【发布时间】:2019-02-27 02:30:35
【问题描述】:

我正在尝试在 Angular 应用程序中实现 DELETE 操作。我希望能够单击一个按钮并删除一个 Firestore 文档,但我的代码不起作用。所以我在我的所有 firestore 操作中使用服务并在我的组件中调用该服务

station.service.ts

import { Injectable } from "@angular/core";
import { AngularFirestore } from "@angular/fire/firestore";
import { Station } from "../../models/station.model";

@Injectable({
  providedIn: "root"
})
export class StationService {
  constructor(private afs: AngularFirestore) {}

  deleteStation(stationId: string) {
    this.afs.doc("stations/" + stationId).delete();
  }
}

station.component.ts

import { Component, OnInit } from "@angular/core";
import { StationService } from "../services/station.service";
import { Station } from "./../../models/station.model";

@Component({
  selector: "app-station",
  templateUrl: "./station.component.html",
  styleUrls: ["./station.component.css"]
})
export class StationComponent implements OnInit {
  stations: Station[];

  constructor(private stationService: StationService) {}

  ngOnInit() {
    this.stationService.getStations().subscribe(data => {
      this.stations = data.map(e => {
        return {
          id: e.payload.doc.data(),
          ...e.payload.doc.data()
        } as Station;
      });
    });
  }

  delete(id: string) {
    if (confirm("Confirm delete operation")) {
      //console.log(id);
      this.stationService.deleteStation(id);
    }
  }
}

我在我的 console.log 消息中找不到 id,它看起来像这样

address: "Somewhere along PTI road, Effurun. Delta State"
name: "Effurun"
region: "South-South"

如何修复我的代码?提醒,这是我第一次使用 Firestore。

【问题讨论】:

  • “我的代码不起作用”有点宽泛。 deleteStation 函数是否运行?如果是这样,它是否将正确的stationId 传递给 Firestore?如果是这样,您的浏览器的开发者控制台上是否显示任何错误?
  • @FrankvanPuffelen deleteStation 函数确实运行,因为我看到了 console.log 消息,但我没有看到 ID。我在station.component.html中调用deleteStation函数就像(click)="delete(station.id)"控制台上也没有错误

标签: javascript angular google-cloud-firestore angularfire2


【解决方案1】:

终于找到bug了。在station.component.tsngOnInit() 方法中,id 被设置为一个对象而不是一个id。像这样将其设置为 id

ngOnInit() {
  this.stationService.getStations().subscribe(data => {
    this.stations = data.map(e => {
      return {
        id: e.payload.doc.id,
        ...e.payload.doc.data()
      } as Station;
    });
  });
}

现在将返回一个字符串类型的实际 id 以及每个对象,然后可以将其传递给delete(id: string) 方法。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-12-27
    • 2013-02-16
    • 1970-01-01
    • 2011-10-31
    • 2019-12-15
    • 2023-01-19
    • 1970-01-01
    • 2014-01-23
    相关资源
    最近更新 更多