0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Ionic + Firebaseで記録するカレンダーアプリを作る その8 ログインユーザーのデータを取得

Last updated at Posted at 2019-11-16

完成イメージ

はじめに

環境は以下の通り
・ionic4
・Nativeとの橋渡しにはcapacitorを使用
・カレンダーについてはionic2-calendarというライブラリーを使用

前回はAngularのGuard機能を使ってログインチェックを実装した。
:point_right:前回の記事はこちら

概要

その5 ユーザー作成と認証から前回までユーザー認証関係の事をしてきたが、実はまだ一番重要は事が終わっていない。

なぜならログインしても全員で共通のカレンダーを取得している事になるからだ。

home.page.ts
// Firebaseからイベント取得
        this.db
          .collection(`events`).snapshotChanges()
          .subscribe(colSnap => {
            this.eventSource = [];
            colSnap.forEach(snap => {
              const event: any = snap.payload.doc.data();
              // ここでのevent.idがhome.page.htmlで使われる
              event.id = snap.payload.doc.id;
              event.startTime = event.startTime.toDate();
              event.endTime = event.endTime.toDate();
              this.eventSource.push(event);
            });
          });

イベントを取得している所をみてみよう。

.collection(`events`)

これではFirestoreのeventsドキュメントから、全てを取得する事になる。

ログインしているユーザーのイベントだけを取得するなら(あくまで1つの例だが、、)以下の様にする必要がある。

 .collection(`users/${user.uid}/events`)

その為に必要なことは
・ユーザー固有のidであるuidを取得
・イベントを追加時に保存する場所をusers/${user.uid}/eventsにする
users/${user.uid}/eventsからイベントを取得する

こんな感じ。

uidを取得してイベントを追加

イベント追加の処理が書いてあるのはhome.service.ts

home.service.ts
// uidを格納する用
currentUser = '';

  constructor(
    private afs: AngularFirestore,
    private afAuth: AngularFireAuth,
    private router: Router,
    private alertCtrl: AlertController
  ) {
// もしログインしているならuserはnullにはならない
    this.afAuth.auth.onAuthStateChanged((user) => {
      if (user != null) {
        this.currentUser = user.uid;
        // コレクションを取得してdayCollectionに格納
        this.dayCollection = this.afs.collection<DayEvent>(`users/${this.currentUser}/events`);
        this.dayEvents = this.dayCollection.snapshotChanges().pipe(
          map(actions => {
            return actions.map(a => {
              const event = a.payload.doc.data();
              const id = a.payload.doc.id;
              return { id, ...event };
            });
          })
        );
      } else {
        this.router.navigateByUrl('/auth');
      }
    });
  }

addNewEvent() {
    const start = this.selectedDate;
    const end = this.selectedDate;
    const eventTitle = this.eventTitle;
    const eventMemo = this.eventMemo;
    const birthControl = this.birthControl;
    end.setHours(end.getHours() + 1);
    const event = {
      title: eventTitle,
       startTime: start,
       endTime: end,
       memo: eventMemo,
       birthControls: birthControl,
       allDay: false
    };
    return this.afs.collection(`users/${this.currentUser}/events`).add(event);
  }

uidを取得してイベントを取得

home.page.ts
 this.afAuth.auth.onAuthStateChanged(user => {
      if (user != null) {
        // Firebaseからイベント取得
        this.db
          .collection(`users/${user.uid}/events`)
          .snapshotChanges()
          .subscribe(colSnap => {
            this.eventSource = [];
            colSnap.forEach(snap => {
              const event: any = snap.payload.doc.data();
              // ここでのevent.idがhome.page.htmlで使われる
              event.id = snap.payload.doc.id;
              event.startTime = event.startTime.toDate();
              event.endTime = event.endTime.toDate();
              this.eventSource.push(event);
            });
          });
      }
    });

これでログインしている人のイベントが取得できた。

最後に

続き:point_down:
その9 オートログイン ストレージにユーザーデータを保存

各ストアで配信されてます。
興味があれば使ってみてください。:relieved:

Apple Store

Google Play

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?