Firebase Hosting に Angular を統合して Firestore に接続
- Cloud Functions を試してみる
- Cloud Functions for Firebaseの開発環境をととのえる
- Firebase Hosting と Firestoreを試す
- Cloud Functions と Firestoreを連携させる
Firebase Hosting を利用して、生のJavaScriptで記述したサンプルからFirestoreに接続して確認できたので、Angular アプリケーションから同様の動作確認を行う。
1.Angular プロジェクト作成 VSCodeで開いて起動
プロジェクト名を、angularfb とし、Angularプロジェクトを新規作成し、VSCodeで起動、とりあえず起動してみる。
> ng new angularfb > code .\angularfb\ > ng serve
OK!
立ち上がることを確認
2.AngularプロジェクトをFirebase と統合
2.1 Firebaseにログイン
> firebase login
しておく。ブラウザが立ちあがり、Googleアカウントにログインする。
2.2 Firebase初期設定
プロジェクトのフォルダで、firebase init を実行
Firebase Hosting と Firestoreを有効化
angularfb> firebase init ######## #### ######## ######## ######## ### ###### ######## ## ## ## ## ## ## ## ## ## ## ## ###### ## ######## ###### ######## ######### ###### ###### ## ## ## ## ## ## ## ## ## ## ## ## #### ## ## ######## ######## ## ## ###### ######## You're about to initialize a Firebase project in this directory: C:\workspaces\Gcp-workspace\Gcp_api_trial\angularfb Before we get started, keep in mind: * You are currently outside your home directory ? Are you ready to proceed? Yes ? Which Firebase CLI features do you want to set up for this folder? Press Space to select features, then Enter to confirm your choices. ( ) Database: Deploy Firebase Realtime Database Rules (*) Firestore: Deploy rules and create indexes for Firestore (*) Functions: Configure and deploy Cloud Functions >(*) Hosting: Configure and deploy Firebase Hosting sites ( ) Storage: Deploy Cloud Storage security rules ( ) Emulators: Set up local emulators for Firebase features : ? What do you want to use as your public directory? public ? Configure as a single-page app (rewrite all urls to /index.html)? Yes + Wrote public/index.html i Writing configuration info to firebase.json... i Writing project information to .firebaserc... + Firebase initialization complete!
2.3 Angularのコンパイルとビルド
Firebase Hosting の出力先を firebase の publicに変更
firebase.json の hosting/public デプロイ対象のフォルダを、Angularのビルド先の フォルダ、distに変更する
“hosting”: {
“public”: “dist”,
3. Angular Fire
3.1 導入
Angular の公式ライブラリ、Angular Fire を導入する。
https://github.com/angular/angularfire
> ng add @angular/fire@next > npm install firebase @angular/fire --save
パッケージ不足エラーになったので適宜インストール
> npm install -g node-gyp > npm install -g node-pre-gyp > npm install --save grpc
Quick Start
https://github.com/angular/angularfire/blob/master/docs/install-and-setup.md
3.2 Firebase 設定の記述
/src/environments/ にある、ファイルをそれぞれ編集
- environment.ts : テスト用環境設定
- environment.prod.ts :本番用環境設定 ng build –prod の場合使用される
記述内容は、FIrebase コンソールから設定を確認し、追記する。
export const environment = { production: false, firebase: { apiKey: '<your-key>', authDomain: '<your-project-authdomain>',// {project-id}.firebaseapp.com databaseURL: '<your-database-URL>',// https://{project-id}.firebaseio.com projectId: '<your-project-id>', storageBucket: '<your-storage-bucket>',// {project-id}.appspot.com messagingSenderId: '<your-messaging-sender-id>' } };
4.Angularアプリケーションの作成
4.1 AppModule で利用モジュールの設定
/src/app/app.module.ts
- Firebaseプロバイダを設定、必要なモジュールを設定
- Firestore利用するために、AngularFirestoreModule をインポート
- 画面でバインディング用に、FomsModuleを インポート
import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { FormsModule } from '@angular/forms'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import { AngularFireModule } from '@angular/fire'; import { AngularFirestoreModule } from '@angular/fire/firestore'; import { environment } from 'src/environments/environment'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, FormsModule, AppRoutingModule, AngularFireModule.initializeApp(environment.firebase), AngularFirestoreModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { }
4.2 AppComponent にコンポーネントの作成
Firebase 単独で Firestoreの動作確認を行った内容を、Angular で実現する。
- AngularFiresotre をDIして使用する。
- save()、load() メソッドを、ボタンのイベントとバインドする。
- load() ボタン押下で、RxJsを使用し、Firestoreのデータを取得
import { Component } from '@angular/core'; import { componentFactoryName } from '@angular/compiler'; import { AngularFirestore } from '@angular/fire/firestore'; import { Observable } from 'rxjs'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.sass'] }) export class AppComponent { firestore: AngularFirestore; title = 'Hot Dog Status'; status = ''; hotDog: Observable; constructor(firestore: AngularFirestore) { this.firestore = firestore; } save(e: any) { const doc = this.firestore.doc("sample/sandwichData"); doc.update({"hotDogStatus":this.status}).then( () => console.log("sucess") ).catch( (res) => console.error("error" + res) ); } load(e: any) { this.hotDog = this.firestore.doc("sample/sandwichData").valueChanges(); this.hotDog.subscribe((res) => { this.status = res["hotDogStatus"]; }); } }
4.3 テンプレートの作成
app.component.html の作成
<h1 id="hotDogStatus">{{title}}:{{status}}</h1> <input type="textField" [(ngModel)]="status" /> <button (click)="save($event)">Save</button> <button (click)="load($event)">Load</button> <router-outlet></router-outlet>
5.実行
> ng serve
5.1 画面から操作
実行ログに出力されるURLにアクセス。http://localhost:4200 起動!
Load ボタンを押下、Firestoreに前回保存した値が取得できた!
取得した値をテキストボックスで変更。双方向バインディングで、タイトルがリアルタイムに変更されるのが見て取れる。
Save ボタン押下で、Firesotreにデータ書き込み成功。
5.2 Firebase コンソールから確認
画面から更新した値が反映されたのが、Firebaseコンソールから確認できた!!!
6. 本番環境へデプロイ
Angularを本番用にビルドし、Firebaseデプロイ
> ng build –prod > firebase deploy --only hosting
以下のようなエラーがでた。。
Error: HTTP Error: 404, Requested entity was not found. PS C:\workspaces\Gcp-workspace\Gcp_api_trial\angularfb> firebase deploy --only hosting === Deploying to 'typea-gcp-api-trial'... i deploying hosting Error: HTTP Error: 404, Requested entity was not found.
https://stackoverflow.com/questions/53049152/firebase-hosting-deploy-error-http-error-404-not-found
firebase init を再実行し、再度ビルド、デプロイ
成功!!!
【参考】デプロイターゲット
https://firebase.google.com/docs/cli/targets?hl=ja
設定
> firebase target:apply hosting angularfb typea-gcp-api-trial.firebaseapp.com
設定クリア
>firebase target:clear hosting angularfb
設定一覧
> firebase target
Resource targets for typea-gcp-api-trial:
[ hosting ]
angularfb (typea-gcp-api-trial.firebaseapp.com)