【问题标题】:Getting the documentid in Angular Firestore [duplicate]在 Angular Firestore 中获取 documentid [重复]
【发布时间】:2019-11-19 19:09:29
【问题描述】:

我无法在 Firestore 中获取文档 ID。我创建了一个随机生成的文档 ID,但是,为了添加一个删除功能,我需要该随机生成的 ID,但无法弄清楚如何访问它。 我也可以创建一个自定义文档 ID,但是,我也无法弄清楚并得到错误。 所以我试图找到一种方法来访问文档 ID 列表中每个项目的文档 ID,这些项目在 html 的 for 循环中打印出来。或者找到一种方法将 doc id 创建为独特的东西,例如解析的图像 url。

import { Component, OnInit } from '@angular/core';
import { Observable, Subject } from 'rxjs';
import { WebcamImage } from 'ngx-webcam';
import { HttpClient } from '@angular/common/http';
import { visionApi } from 'src/environments/environment';
import { Router } from '@angular/router';
import { AngularFireAuth } from '@angular/fire/auth';
import { AuthorizationService } from '../auth-service.service';
import { AngularFirestoreModule, AngularFirestore, AngularFirestoreCollection } from '@angular/fire/firestore';
import { BusinessCardServiceService } from '../business-card-service.service';

interface BusinessCard {

  imageUrl: string;
  name: string;
  email: string;
  phone: string;
  fullText: string;
}

@Component({
  selector: 'app-root',
  templateUrl: './web-cam.component.html',
  styleUrls: ['./web-cam.component.scss']
})
export class WebCamComponent implements OnInit {
  public showWebcam = true;
  public webcamImage: WebcamImage = null;
  private trigger: Subject<void> = new Subject<void>();
  public base64;
  public url = `https://vision.googleapis.com/v1/images:annotate?key=${visionApi.key}`;
  public parsedImage;
  email: string;
  fullText: string;
  name: string;
  phone: string;
  imageUrl: string;
  uid = JSON.parse(localStorage.getItem('uid'));

  private cardCollection: AngularFirestoreCollection<BusinessCard>;
  businessCards: Observable<BusinessCard[]>;

  constructor(private http: HttpClient,
              public afAuth: AngularFireAuth,
              public router: Router,
              private dashService: AuthorizationService,
              private afs: AngularFirestore,
              public bcService: BusinessCardServiceService) {

  }
  public handleImage(webcamImage: WebcamImage): void {
    this.webcamImage = webcamImage;
    this.base64 = this.webcamImage.imageAsBase64;
    this.imageUrl = this.webcamImage.imageAsDataUrl;
    this.parsedImage = this.base64.replace(/^data:image\/(png|jpg|jpeg);base64,/, '');
    const request: any = {
      'requests': [
        {
          'image': {
            'content': this.parsedImage
          },
          'features': [
            {
              'type': 'TEXT_DETECTION'
            }
          ]
        }
      ]
    };
    console.log(request);
    console.log(this.parsedImage);
    this.http.post(
      this.url,
      request
    ).subscribe((results: any) => {
      console.log('RESULTS');
      console.log(results);
      console.log(results.responses[0].fullTextAnnotation.text);
      this.fullText = results.responses[0].fullTextAnnotation.text;
      this.email = JSON.stringify(this.fullText.match(/[a-zA-Z0-9-_.]+@[a-zA-Z0-9-_.]+/));
      this.name = JSON.stringify(this.fullText.match(/([A-Za-z]+),\\s*([A-Za-z]+)\\s*([A-Za-z]+)/));
      this.phone = JSON.stringify(this.fullText.match(/\(?([0-9]{3})\)?([ .-]?)([0-9]{3})\2([0-9]{4})/));
      // tslint:disable-next-line: max-line-length
      this.bcService.create(this.fullText, this.email, this.name, this.phone, this.imageUrl, this.uid);



  });

  }
  public ngOnInit(): void {
      // tslint:disable-next-line: max-line-length
      this.cardCollection = this.afs.collection<BusinessCard>('Users/' + this.uid + '/BusinessCards' + this.uid);
      this.businessCards = this.cardCollection.valueChanges();

  }

  public triggerSnapshot(): void {
    this.trigger.next();
  }

  public get triggerObservable(): Observable<void> {
    return this.trigger.asObservable();
  }
}
import { Injectable } from '@angular/core';
import { AngularFirestoreModule, AngularFirestore, AngularFirestoreCollection, AngularFirestoreDocument } from '@angular/fire/firestore';
import { Observable } from 'rxjs';
import { WebcamImage } from 'ngx-webcam';

interface BusinessCard {

  imageUrl: string;
  name: string;
  email: string;
  phone: string;
  fullText: string;
}



@Injectable({
  providedIn: 'root'
})
export class BusinessCardServiceService {
  uid: string;
  email: string;
  fullText: string;
  name: string;
  phone: string;
  imageUrl: string;
  public webcamImage: WebcamImage = null;
  cardObj: string;
  cardref: AngularFirestoreCollection<BusinessCard>;
  constructor(private afs: AngularFirestore) { }

  cardRef: AngularFirestoreCollection<BusinessCard>;
  card$: Observable<BusinessCard[]>;

  create(fullText: string, email: string, name: string, phone: string, imageUrl: string, uid: string) {
    this.fullText = fullText;
    this.email = email;
    this.name = name;
    this.phone = phone;
    this.imageUrl = imageUrl;
    this.uid = uid;
    this.afs.doc('Users/' + this.uid).set({
    });
    this.afs.collection('Users/' + this.uid + '/BusinessCards' + this.uid).add({
      fullText: this.fullText,
      name: this.name,
      phone: this.phone,
      imageUrl: this.imageUrl,
      email: this.email,
      uid: this.uid
    });


  }

  getCard() {
    return this.afs.collection('Users/' + this.uid + '/BusinessCards' + this.uid).snapshotChanges();
  }

 // deletePolicy(cardId: string){
 //   this.cardId = cardId
 //   this.afs.doc('Users/' + this.uid + '/BusinessCards' + this.uid + this.cardId).delete();

}

<ul>
    <div *ngFor='let card of businessCards | async'>
        <div>{{card.name}} <button class="updateButton">Update Name</button></div>
        <div>{{card.email}} <button class="updateButton">Update Email</button></div>
        <div>{{card.phone}} <button class="updateButton">Update Phone Number</button></div>
        <img [src]='card.imageUrl' />
        <div><button class="DeleteButton">Delete Card</button></div>
    </div>
</ul>

【问题讨论】:

    标签: angular typescript google-cloud-firestore angularfire2


    【解决方案1】:

    snapshotChanges() 是返回包含文档 ID 的文档元数据的函数。 Here is an implementation Angular 中的那个函数。获取ID后,可以通过these guidelines删除数据。查看here 以获取有关类似问题的一些回复。

    【讨论】:

      【解决方案2】:

      您似乎正在使用valueChanges 订阅WebCamComponent 中的此查询

      this.cardCollection = this.afs.collection<BusinessCard>('Users/' + this.uid + '/BusinessCards' + this.uid);
      this.businessCards = this.cardCollection.valueChanges();
      

      但是valueChanges 没有return all the metadata,它只返回值。您也想使用snapshotChanges (see here) 来获取密钥。

      您需要解压结果,当然要在名片中包含id。 id 将在结果的 doc.id 成员上,而您已经拥有的其余字段将是 doc.data 成员。

      由于这会返回更多元数据(不仅是 id,而且还涉及到什么样的更改,都在 DocumentChangeAction[] 中),您将需要类似于上面文档中示例的代码来解压它(注意:我没有在您的代码的完整上下文中测试这个确切的示例,但一般形式应该适合您):

          this.businessCards = this.cardCollection.snapshotChanges().pipe(
            map(actions => actions.map(a => {
              const data = a.payload.doc.data() as BusinessCard;
              data.id = a.payload.doc.id;  // assumes member `id` is on BusinessCard
              return data;
            }))
          );
      

      【讨论】:

        猜你喜欢
        • 2019-04-14
        • 1970-01-01
        • 1970-01-01
        • 2021-01-08
        • 2020-11-08
        • 2018-07-23
        • 2021-06-23
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多