Angular 與 Firebase

使用Firebase

前言

目前使用版本: 8.2.5

官方文件: https://firebase.google.com/docs/auth/web/firebaseui

安裝

Using Firebase via CDN

./src/index.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<!-- Insert these scripts at the bottom of the HTML, but before you use any Firebase services -->
<!-- Firebase App (the core Firebase SDK) is always required and must be listed first -->
<script src="https://www.gstatic.com/firebasejs/8.2.5/firebase-app.js"></script>

<!-- If you enabled Analytics in your project, add the Firebase SDK for Analytics -->
<script src="https://www.gstatic.com/firebasejs/8.2.5/firebase-analytics.js"></script>

<!-- Add Firebase products that you want to use -->
<script src="https://www.gstatic.com/firebasejs/8.2.5/firebase-auth.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.2.5/firebase-firestore.js"></script>

<script src="https://www.gstatic.com/firebasejs/ui/4.6.1/firebase-ui-auth.js"></script>
<link type="text/css" rel="stylesheet" href="https://www.gstatic.com/firebasejs/ui/4.6.1/firebase-ui-auth.css" />

新建一個config檔案: src/app/xxx_config.ts

1
2
3
4
5
6
7
8
9
10
export const firebaseConfig:object = {
apiKey: "YOUR_API_KEY",
authDomain: "YOUR_PROJECT_ID.firebaseapp.com",
databaseURL: "https://YOUR_PROJECT_ID.firebaseio.com",
projectId: "YOUR_PROJECT_ID",
storageBucket: "YOUR_PROJECT_ID.appspot.com",
messagingSenderId: "SENDER_ID",
appId: "APP_ID",
measurementId: "G-MEASUREMENT_ID",
};

./src/app/logging-page/logging-page.component.ts

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import { firebaseConfig } from '../xxx_config';

export class LoggingPageComponent implements OnInit {

constructor() {}

@Input() firebaseConfig: object;

ngOnInit(): void {
const firebase = globalThis.firebase;
const firebaseui = globalThis.firebaseui;
firebase.initializeApp(firebaseConfig);
var ui = new firebaseui.auth.AuthUI(firebase.auth());
//...
var uiConfig = {
//...
signInSuccessUrl: '/setting',
}
ui.start('#firebaseui-auth-container', uiConfig);

}

}

./src/app/logging-page/logging-page.component.html

1
<div id="firebaseui-auth-container" class="self-center"></div>

Using Firebase via NPM

1
$ npm install firebaseui --save
1
2
var firebase = require('firebase');
var firebaseui = require('firebaseui');

實作

在Angular使用Firebase

1
2
$ npm install firebase --save
$ npm install firebaseui --save

在需要使用auth的component中引入firebase模組

1
2
import firebase from 'firebase/app';
import * as firebaseui from 'firebaseui';

./src/app/logging-page/logging-page.component.ts

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import firebase from 'firebase/app';
import * as firebaseui from 'firebaseui';
import { firebaseConfig } from '../xxx_config';

export class LoggingPageComponent implements OnInit {

constructor() {}

@Input() firebaseConfig: object;

ngOnInit(): void {
// const firebase = globalThis.firebase;
// const firebaseui = globalThis.firebaseui;
firebase.initializeApp(firebaseConfig);
var ui = new firebaseui.auth.AuthUI(firebase.auth());
//...
var uiConfig = {
//...
signInSuccessUrl: '/setting',
}
ui.start('#firebaseui-auth-container', uiConfig);

}

}

將firebaseui.css建立在 ./src/assets/ 下,才能夠直接被Angular的index.html引用

./src/index.html

1
<link rel="stylesheet" href="assets/firebaseui.css">

自訂FirebaseAuth介面

由於Angular在component中的scss會編譯為scoped css,會抓不到像是 .firebasui-container這樣的元件,因此要將code寫在styles.scss這個檔案中,才會被編譯為全域css。

./src/styles.scss

1
2
3
4
5
#firebaseui-auth-container{
.firebaseui-container {
box-shadow: none;
}
}
閱讀全文

Angular Basic

官方文件: https://angular.io/guide/setup-local

1
npm install -g @angular/cli
1
ng new account-manager

從AngularJS到Angular

https://angular.io/guide/ajs-quick-reference

Angular 詞彙表 https://angular.tw/guide/glossary

設定Routing

./src/app/app-routing.module.ts

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { Component1 } from './component1/component1.component';
import { Component2 } from './component2/component2.component';

const routes: Routes = [
{ path: '', component: Component1 },
{ path: 'component2', component: Component2 },
{ path: '**', redirectTo: '/', pathMatch: 'full' },
];

@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }

其中的const routes就是用來自訂網址導向哪個component的設定

1
2
3
4
5
6
const routes: Routes = [
{ path: '', component: Component1 },
{ path: 'component2', component: Component2 },
{ path: '**', redirectTo: '/', pathMatch: 'full' },
];

./src/app/app.component.html

1
<router-outlet></router-outlet>

使用HTTPClient

1
import { HttpClient } from '@angular/common/http';
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
export class Component2 implements OnInit {

constructor(private http: HttpClient) {}

get_data = function():void{
this.http
.get("http://localhost:3000/data",
{observe:'body', responseType: 'json'})
.subscribe((data)=>{
this.data = data;

// console.log(this.data)
})
}

}


設定伺服器導回根目錄

問題: 當build後用http-server或live-server卻無法開啟 /component2 之類的網址?

解答:

用http-server或live-server開啟 /index.html 是沒問題的,但是當它找不到 /component2/index.html 時,就會報錯。因此要設定在找不到時,回到根目錄找尋/index.html

在官方文件中也有提到,Routed apps must fallback to index.html

https://angular.io/guide/deployment#routed-apps-must-fallback-to-indexhtml

以live-server為例,在cmd中加入 --entry-fire=./index.html

1
live-server --entry-file=./index.html

或是安裝angular-http-server,然後在cmd中指定其根目錄

1
angular-http-server --path ./dist

控制build部署時的URL

問題: 當build且deploy至有handler的伺服器時找不到main.js?

解答:

例如,輸出的資料夾為 /dist,則 /dist/index.html 所預設的是在同一資料夾裡的 /dist/main.js,連結則為 main.js。當handler想要避免把檔案都塞在根目錄下,而是放在 /SOMEWHERE/ 下時,要如何將路徑從main.js修改為/SOMEWHERE/main.js呢?

答案是,在ng build後方加上參數 --deploy-url=/SOMEWHERE/

更多參數: https://angular.io/cli/build

使用RxJS設定Loading的計時器

問題: 如何用RxJS來設定Loading圖示的計時器?

解答:

首先,引入rxjs的 Subject,以及將會使用到的operator: debounceTimetap

1
2
import { Subject } from 'rxjs';
import { debounceTime, tap } from 'rxjs/operators';

Subject是一種可以被多方監聽的Observable。

A Subject is like an Observable, but can multicast to many Observers. Subjects are like EventEmitters: they maintain a registry of many listeners.

https://rxjs-dev.firebaseapp.com/guide/subject

首先,建立一個Subject的實例,把它叫做is_editing_xxx$。請注意結尾是用 $ 來提示這是一個Subject。

我們在ngOnInit中呼叫這個Subject,讓它執行一個pipe,其中先啟動Loading圖示,經過1000毫秒後,關閉Loading圖示。然後我們訂閱這個Subject。

接著,在需要使用這個Subject的地方,例如click_sth中,我們寫下 this.is_editing_xxx$.next(),就會讓它執行下一步。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
is_editing_xxx$ = new Subject<string>();

ngOnInit(){
this.is_editing_xxx$.pipe(
tap(() => { this.loading_userconfig = true; }),
debounceTime(1000),
tap(() => {
this.loading_userconfig = false;
})
).subscribe();

}

click_sth(){
this.is_editing_xxx$.next();
}

另一種寫法是創造一個變數 is_editing_xxx,注意,這個變數的結尾沒有$的符號,如此一來,我們不需要在ngOnInit中,就可以設定 is_editing_xxx$ 的pipe和訂閱它。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
is_editing_xxx$ = new Subject<string>();

is_editing_xxx = this.is_editing_xxx$
.pipe(
tap(() => { this.loading_userconfig = true; }),
debounceTime(1000),
tap(() => {
this.loading_userconfig = false;
}))
.subscribe();

ngOnInit(){
}

click_sth(){
this.is_editing_xxx$.next();
}
閱讀全文

Angular 與 MaterialUI

Angular Material官方文件

https://material.angular.io/

Using Material UI via CLI

1
$ ng add @angular/material

自訂主題

https://material.angular.io/guide/theming

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
// MATERIAL-UI
@import '~@angular/material/theming';
@include mat-core();


$mat-cyan-qs: (
50: #e0f7fa,
100: #b2ebf2,
200: #80deea,
300: #4dd0e1,
400: #26c6da,
500: #2EC5CE,
600: #00acc1,
700: #0097a7,
800: #00838f,
900: #006064,
A100: #84ffff,
A200: #18ffff,
A400: #00e5ff,
A700: #00b8d4,
contrast: (
50: $dark-primary-text,
100: $dark-primary-text,
200: $dark-primary-text,
300: $dark-primary-text,
400: $dark-primary-text,
500: $light-primary-text,
600: $light-primary-text,
700: $light-primary-text,
800: $light-primary-text,
900: $light-primary-text,
A100: $dark-primary-text,
A200: $dark-primary-text,
A400: $dark-primary-text,
A700: $dark-primary-text,
)
);

// $candy-app-primary: mat-palette($mat-indigo);
$candy-app-primary: mat-palette($mat-cyan-qs);
$candy-app-accent: mat-palette($mat-indigo);

// The warn palette is optional (defaults to red).
$candy-app-warn: mat-palette($mat-red);

// Create the theme object. A theme consists of configurations for individual
// theming systems such as `color` or `typography`.
$candy-app-theme: mat-light-theme((
color: (
primary: $candy-app-primary,
accent: $candy-app-accent,
warn: $candy-app-warn,
)
));

// Include theme styles for core and each component used in your app.
// Alternatively, you can import and @include the theme mixins for each component
// that you are using.
@include angular-material-theme($candy-app-theme);


使用Mat-Dialog

1
$ ng g c ./dialog/dialog-edit-member
1
2
3
4
5
6
7
8
9
10
11
12
13
14
open_dialog_edit_member(member) {
this.member_on_editing = JSON.parse(JSON.stringify(member));
const dialogRef = this.dialog.open(DialogEditMemberComponent, {
width: "400px",
height: "300px",
data: {
member_on_editing: this.member_on_editing,
member: member,
}
});
dialogRef.afterClosed().subscribe(result => {
console.log('The dialog was closed');
});
}
閱讀全文