套接字未在angular-firebase上连接以获得实时更新

时间:2019-01-16 11:24:54

标签: javascript angular firebase firebase-realtime-database

您好,我是angular和firebase的新手,尝试连接我的angular应用程序以获取实时数据更新,我从此网址-https://www.djamware.com/post/5bbf534580aca7466989441c/angular-6-firebase-tutorial-firestore-crud-web-application实现了该过程,当页面加载时,我正在获取初始数据服务的getOrder()函数。

在我的应用程序组件中-

import * as firebase from 'firebase';
import firestore from 'firebase/firestore';
import { environment } from '../environments/environment'; // here my configuration is

const settings = {timestampsInSnapshots: true}

ngOnInit(){
    firebase.initializeApp(environment.firebase);
    firebase.firestore().settings(settings);
}

在我的firebase.service中-

ref = firebase.firestore().collection('orders');
getOrders(): Observable<any> {
      console.log('on get orders snapshot');
      return new Observable((observer) => {
        this.ref.onSnapshot((querySnapshot) => {
          let boards = [];
          querySnapshot.forEach((doc) => {
            let data = doc.data();
            observer.next({
              driver_status: data.driver_status,
              food_status: data.food_status,
            });
          });
          observer.next(boards);
        });
      });
    }

    getOrder(id: string): Observable<any> {
      return new Observable((observer) => {
        this.ref.doc('ref-'+id).get().then((doc) => {
          let data = doc.data();
          observer.next({
            driver_status: data.driver_status,
            food_status: data.food_status,
          });
        });
      });
    }

在我的详细信息组件中-



displayedColumns = ['driver_status', 'food_status'];
dataSource = new OrderDataSource(this.fs);

public fireOrder: Observable<any[]>;
ngOnInit(){
this.fs.getOrder(this.order.id).subscribe(res =>{
  this.fireOrder = res;
});
}
--------------------------
export class OrderDataSource extends DataSource<any> {

  constructor(private fs: FirebaseService) {
    super();
    console.log('in OrderDataSource constructor');
    this.connect();
  }

  connect() {
    console.log('in connect');
    return this.fs.getOrders();
  }

  disconnect() {
  }
}

我正在从Firebase获取初始数据,但是它没有连接套接字以获取实时数据。

1 个答案:

答案 0 :(得分:1)

doc()。get()返回一个promise,而不是一个流(Observable)。有了承诺,如果这是您的目标,则可以利用仅获取一次数据的优势。为了首先获取数据并听取更改,您需要使用doc().onSnapshot() method

此外,我建议尝试Angular's @angular/fire package(angular / angularfire2)进行Angular + Firebase开发,因为已经有了很多官方文档,特定的支持和问题。有了它,有可能将getOrder方法简化为:

getOrder(id: string): Observable<Order> {
    console.log('on get order snapshot');
    return db.doc<Order>(`orders/${id}).valueChanges();
}