LoginSignup
0
0

More than 3 years have passed since last update.

Firebase 条件分岐をしてデータの読み取り(Firestore)

Posted at

はじめに

FirebaseのデータベースFirestoreで、条件分岐をしてからデータを取得する例です。
また、取得したデータの数をカウントしてます。

私の環境
・Ionic + Angular

whereを使う

eventの中身がこんな感じだとする。

event.model.ts
export class Event {
         constructor(
           public id?: string,
           public title?: string,
           public periods?: boolean,
         ) {}
       }
home.page.ts
import { AngularFireAuth } from '@angular/fire/auth';
import { AngularFirestore } from '@angular/fire/firestore';

@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss']
})
export class HomePage implements OnInit {
private eventCount;
 private periodCount;


constructor(
    private afAuth: AngularFireAuth,
    private db: AngularFirestore
  ) { }

  ngOnInit() {
    this.afAuth.auth.onAuthStateChanged((user) => {
      if (user != null) {

      // events以下の全てのドキュメントを取得してカウント
        this.db
          .collection(`users/${user.uid}/events`)
          .snapshotChanges()
          .subscribe(c => {
            this.eventCount = c.length;
          });

      // events以下のドキュメントでperiodsプロパティがtrueのドキュメントを取得
        this.db
           .collection(`users/${user.uid}/events`, ref =>
             ref.where('periods', '==', true)
           )
           .snapshotChanges()
           .subscribe(c => {
             this.periodCount = c.length;
           });
      }
    });
  }

参考

}

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0