在Angular Firestore中获取documentid

时间:2019-11-19 19:09:29

标签: angular typescript google-cloud-firestore angularfire2

我无法在Firestore中获取文档ID。我创建了一个随机生成的文档ID,但是,要添加删除功能,我需要该随机生成的ID,无法弄清楚如何访问它。 我也可以创建一个自定义文档ID,但是,我也无法弄清楚该错误并得到错误。 因此,我试图找到一种方法来访问文档ID,即在html的for循环中打印出的列表中每个项目的文档ID。或者找到一种方法来将文档ID创建为唯一的内容(例如,解析的图片网址)。

data=[];
tempData =[] ;
getTableData(){
    let filterData = [];
    this.tempData.forEach(element => {
      if(new Date(element.sighnUpStarTimeStamp) > this.dateTimeRange[0] && new 
          Date(element.sighnUpEndTimeStamp) < this.dateTimeRange[1]){
        filterData.push(element);
      }
    });
    this.data = filterData;

  }
 driver.manage().deleteAllCookies();
 driver.get(data.getData().getProperty("url"));
 Thread.sleep(5000);
 log.info("Successed Login ");
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();
  }
}

2 个答案:

答案 0 :(得分:0)

snapshotChanges()是用于返回包含文档ID的文档元数据的函数。 Here is an implementation在Angular中的功能。一旦获得ID,就可以在these guidelines之后删除数据。看看here,您会获得关于类似问题的一些答案。

答案 1 :(得分:0)

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

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

但是valueChanges不是return all the metadata,它只返回值。您还想使用snapshotChangessee here)来获取密钥。

您将需要打开结果包装,当然要在商业名片中包含id。该ID将位于结果的doc.id成员上,而您已经拥有的其余字段将成为doc.data成员。

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

    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;
      }))
    );