извлечение коллекции firestore, документа с использованием angular4

#angular #firebase #google-cloud-firestore

#angular #firebase #google-облако-firestore

Вопрос:

У меня есть база данных firebase, и я пытаюсь получить ее через angular. удалось подключиться к базе данных, однако не удалось прочитать данные … это то, что я сделал, и не смог получить данные…

Я, конечно, чего-то не хватает, не мог бы кто-нибудь подсказать или предоставить ссылку?

 import { Component } from '@angular/core';
import { Observable } from 'rxjs/Observable';

import {AngularFirestore, AngularFirestoreCollection, AngularFirestoreDocument} from 'angularfire2/firestore';
import { Http } from '@angular/http';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  private itemsCollection: AngularFirestoreCollection<UserProfiles>;
  items: Observable<UserProfiles[]>;
  constructor(private afs: AngularFirestore) {
    this.itemsCollection = afs.collection<UserProfiles>('UserProfiles');
    this.items = this.itemsCollection.valueChanges();
  }

}

export class UserProfiles{
  id?: string;
  active?: string;
  company?: string;
  email?: string;
  firstName?: string;
  lastName?: string;
  password?: string;
  userId?: string;
  userType?: string;
}
  

Комментарии:

1. Пожалуйста, уточните в своем вопросе, как вы конкретно используете items . Используете ли вы это в своем шаблоне? Если вы планируете использовать только результат items в этом компоненте, как и в большинстве наблюдаемых объектов, вам нужно subscribe() обратиться к нему. this.items.subscribe(data => console.log(data)) в этом компоненте или что-то вроде *ngFor="let item of items | async" . github.com/angular/angularfire2/blob/master/docs/firestore /…

Ответ №1:

Вам нужно было бы subscribe() использовать Observable<UserProfiles[]>; созданное valueChanges()() , в данном случае items свойство класса, для извлечения / использования данных:

 import { Component } from '@angular/core';
import { Observable } from 'rxjs/Observable';

import {AngularFirestore, AngularFirestoreCollection, AngularFirestoreDocument} from 'angularfire2/firestore';
import { Http } from '@angular/http';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  private itemsCollection: AngularFirestoreCollection<UserProfiles>;
  items: Observable<UserProfiles[]>;
  constructor(private afs: AngularFirestore) {
    this.itemsCollection = afs.collection<UserProfiles>('UserProfiles');
    this.items = this.itemsCollection.valueChanges();
    this.items.subscribe(data => console.log(data)); // subscribe and log emitted data
  }

}
  

В противном случае, если вы используете items в шаблоне, в качестве одного из вариантов вы можете использовать async канал для подписки на items наблюдаемое и визуализации данных:

 <ul>
  <li *ngFor="let item of items | async">{{item.someProperty}}</li>
</ul>