AngularFirestoreCollection snapshotChanges()不会在服务构造函数

时间:2017-11-07 05:06:19

标签: angular typescript firebase google-cloud-firestore

我有一个用户服务,我将添加到我的firebase云firestore beta服务数据库中管理角色。我已经将集合和一些文档添加到数据库中。该服务被注入另一个方法,所以我认为服务中的构造函数将触发并加载集合,但是snapshotChanges()永远不会发出值,因为数据永远不会记录到控制台,因此集合永远不会加载。

想知道在服务构造函数中运行此代码是否存在问题?

app.module.ts

import { Component } from '@angular/core';
import { AuthService } from './auth.service';
import {UserService} from './user.service';
import {Router} from '@angular/router';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  constructor(private auth: AuthService, router: Router, private userService: UserService) {
    auth.user$.subscribe(user => {
      if (user) {
          const returnUrl = localStorage.getItem('returnUrl');
          router.navigateByUrl(returnUrl);
          userService.getAppUsers();
          userService.addUser(user);
      }
    });
  }

}

user.service.ts

import { Injectable } from '@angular/core';
import { AngularFirestore, AngularFirestoreCollection, AngularFirestoreDocument } from 'angularfire2/firestore';
import * as firebase from 'firebase';
import { Observable } from 'rxjs/Observable';

interface AppUser {
  name: string;
  email: string;
  isAdmin: boolean;
}

@Injectable()
export class UserService {
  AppUserCollection: AngularFirestoreCollection<AppUser>;
  AppUsers$: Observable<any[]>;

  constructor(public db: AngularFirestore) {
    this.AppUserCollection = this.db.collection('users');
  }

  getAppUsers() {
    alert("here");
    return this.AppUsers$ = this.AppUserCollection.snapshotChanges()
    .map(actions => {
      alert('there');
      return actions.map(a => {
        const data = a.payload.doc.data() as AppUser;
        console.log('Data' + data);
        const id = a.payload.doc.id;
        return { id, data };
      });
    });
  }
    addUser(user: firebase.User) {
      this.db.collection('users').add({'name': user.displayName, 'email': user.email, 'isAdmin': false});
  }
    // }
}

1 个答案:

答案 0 :(得分:0)

尝试订阅this.AppUsers。

this.AppUsers = this.AppUserCollection.snapshotChanges()
    .map(actions => {
    return actions.map(a => {
        const data = a.payload.doc.data() as AppUser;
        console.log('Data' + data);
        const id = a.payload.doc.id;
        return { id, data };
    }).subscribe();