AngularFirestore数据库,使用“ onSnapshot”更改数据时,HTML表未更新

问题描述 投票:2回答:1

我正在使用onSnapshot获取数据库中的实时更新。

我使用此代码获取表的数据:

Service.ts

export class ExtractorService {

  constructor(private fstore: AngularFirestore) { }

  sampleFunction() {
    return new Promise(resolve => {
      this.fstore.firestore.collection('banned').doc('words')
      .onSnapshot(function(doc) {
        //console.log("from service (WORDS): ", doc.data().cars)
        resolve(doc.data().cars);
      }); 
    });
  } 

为了获取服务上的数据,我将此代码用于Component.ts

export class sampleComponent implements OnInit {

banWords = [];

  constructor(private extractorService: ExtractorService) {}

  ngOnInit() {
    this.loadBannedWords()
  }

 loadBannedWords(){
      this.extractorService.sampleFunction().then(data => {
      this.banWords = (data as unknown as string[]);
      console.log("words: ", this.banWords )
    })

  }

然后我使用此HTML加载表:

<tr *ngFor ="let item of banWords ; index as i ">
      <td>{{ i+1 }}</td>
      <td>{{ item }}</td>

然后我的数据库看起来像这样:

enter image description here

这里的问题是当我在数据库中添加,更新或删除数据时,该表未自动更新或重新加载。我需要刷新页面才能更新表。

如何在更新数据库时更新表?

angular firebase google-cloud-firestore angularfire
1个回答
1
投票

由于您要返回承诺,因此只能从服务中获取一次数据。 Promise仅返回一次值,然后它们完成。您需要的是一个Observable。

您可以在服务中定义一个公共的Observable。

类似:

export class ExtractorService {

  public myObservable$: Observable<Array<string>>`;

  constructor(private fstore: AngularFirestore) {
    this.myObservable$ = this.fstore.firestore.collection('banned').doc('words')
        .onSnapshot.pipe(map(doc -> doc.data().cars));
  }
}

这样,您的Observable将通过仅将汽车交还给其所有订户来操纵快照Observable。

定义了Observable之后,可以在需要数据的每个组件中进行订阅。例如]

export class SomeComponent {

  private onDestroy$ = new Subject();

  constructor(private extractorService: ExtractorService) { }

  public ngOnInit() {
    this.extractorService.myObservable$
        .pipe(takeUntil(this.onDestroy$))
        .subscribe(data => {
      this.banWords = data;
      console.log("words: ", this.banWords )
    });
  }

  public ngOnDestroy() {
    // Unsubscribe all subscriptions of this component.
    this.onDestroy$.next();
  }
}

使用Observables的好处是,您也可以直接在模板中使用它们。例如,如果您的服务在组件中是公共的,则可以使用模板中的异步管道来访问可观察对象的当前值:

<div *ngFor="let car of extractorService.myObservable$ | async">
  {{ car }}
</div>
© www.soinside.com 2019 - 2024. All rights reserved.