LoginSignup
20
23

More than 1 year has passed since last update.

angular + firebase逆引きサンプル集

Last updated at Posted at 2018-09-27

概要

https://github.com/angular/angularfire
@angular/fireを試したメモを記載します。
データベースはfirestoreを使う想定です。

初期設定

https://github.com/angular/angularfire2/blob/master/docs/install-and-setup.md
正直、公式通りにやるのが一番だと思うのでリンクを張るだけにしておきます。
認証情報はfirebaseコンソールの「アプリを追加」を行うと確認できるようになります。

Googleアカウントでログインさせたい

  constructor(public auth: AngularFireAuth) {}

  login() {
    this.auth.signInWithPopup(new auth.GoogleAuthProvider());
  }

  logout() {
    this.auth.signOut();
  }

Google認証を簡単に実装することができます。
firebaseコンソールでGoogle認証を有効にする必要があります。

collectionを取得したい

  constructor(private afs: AngularFirestore): {
    this.items = afs.collection<Item>('items').valueChanges();
  }

collectionとvalueChangesを使います。
返り値はObservableなのでasync pipeなどと組み合わせる必要があります。

documentを取得したい

  constructor(private afs: AngularFirestore): {
    this.item = afs.doc<Item>('items/1').valueChanges();
  }

docを使うところ以外はだいたいcollectionと同じです。

documentを作成したい

  constructor(private afs: AngularFirestore): {
    const shirtsCollection = afs.collection<Item>('tshirts');
    shirtsCollection.add({ name: 'item', price: 10 });
  }

addでdocumentを作成した場合、idは自動生成されます。

idを指定してdocumentを作成したい

  constructor(private afs: AngularFirestore) {
    this.itemDoc = afs.doc<Item>('items/1');
  }

  create(item: Item) {
    this.itemDoc.set(item);
  }

setを使うとidを指定してdocumentを作成することができます。
すでにデータが存在するidの場合はdocumentが上書きされるので注意が必要です。

documentを更新したい

  constructor(private afs: AngularFirestore) {
    this.itemDoc = afs.doc<Item>('items/1');
  }

  update(item: Item) {
    this.itemDoc.update(item);
  }

updateを使うと上書きではなく、指定したfieldだけを更新をすることができます。

documentを削除したい

  constructor(private afs: AngularFirestore) {
    this.itemDoc = afs.doc<Item>('items/1');
  }

  delete() {
    this.itemDoc.delete();
  }

deleteでdocumentを削除できます。

fieldの値で絞り込みたい

afs.collection('items', ref => ref.where('size', '==', 'large'))

クエリはコールバックで渡す必要があります。

fieldの値で並び替えたい

afs.collection('items', ref => ref.orderBy('country', 'desc'))

だいたいwhereと同じです。

本人だけ見れるように制限したい

service cloud.firestore {
  match /databases/{database}/documents {
    match /users/{user} {
      allow read, write: if request.auth != null && request.auth.uid == user;
    }
  }
}

専用のsyntaxでfirestore.rulesを記述します。
client側のクエリがrulesの範囲内でないとパーミッションエラーが発生します。

作成日時を保存したい

import { firestore } from "firebase/app";

firestore.FieldValue.serverTimestamp();

いろいろやり方はあると思いますが、firebaseが提供している方法を紹介しておきます。

collectionを取得したときにidも含めたい

this.items = afs
  .collection('items')
  .valueChanges({ idField: "id" });

valueChangesはデフォルトだとdocumentのidを含みませんが、idFieldを指定することでidも返すことができるようになります。

20
23
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
20
23