angular8+firebase real-time database firebase.pdf- core angular features - rapid development - code...
TRANSCRIPT
Angular8+Firebase Real-Time DatabaseAsst.Prof.Wichan Thumthong
https://bit.ly/2Xx6TP3
Angular- Angular Refresher- Angular Material- Angularfire2- NgRx
- HTML- CSS, Saas, Less- Basic JavaScript- Programming Fundametals
(Functions, Conditions, Loops)
What you should know?
What is Angular?- Frontend/Client side JavaScript Framework- Create and Maintained by Google- Use to buid powerful Single Page Application- Part of the very powerful MEAN stack- HTML would be dynamic web applications- Integrated other solutions (.net, ionic,
NativeScript)- Open source- Large community
What is Angular is Not?- A server side framework/technology- JavaScript library- Design pattern- Platform- Language- Plugin- Entension
What is Angular?
JavaScript Framework
Single Page Application
TypeScript, JavaScript
Client-Side Web Apps
Native&Hybrid Mobile Application
Why is Angular awesome?- MVC design pattern- SPA support- Unit Testing Ready- JavaScript/TypeScript- Dynamic Content- Core Angular Features- Rapid Development - Code Organization and Productivity- Cross Platform- Google
Core Angular Features- Components- Services- Routing- Testing- Build Tools- Data Binding- Templating- HTTP Module- Form Module
- Directives- Pipes- Events- Animation- TypeScript
Developer Tools Node and AngularCLInode -vng version
vscode-iconsAngular 8 Snippets angular2-switcher
VScode Extensions
Install and Project Setup with the Angular CLI- Install Angular CLI
- npm install -g @angular/cli
- Create Angular Project- cd desktop (change directiory to your drive)- ng new myFirstApp - (select routing and css)
- Open Project in VS Code- Angular App Start
- ng serve --open
- Run http://localhost:4200/ - Generate Componets
- ng g c product
Angular Interpolation
Core concepts Single HTML page which is continuously re-rendered by Angular
HeaderComponent
FooterComponent
SidebarComponent ItemComponent
Install Bootstap, jQuery and Font Awesomenpm install bootstrap jquery
Update file angular.json (stop and re-run)
"styles": [ "src/styles.css", "node_modules/bootstrap/dist/css/bootstrap.css" ], "scripts": [ "node_modules/jquery/dist/jquery.js", "node_modules/bootstrap/dist/js/bootstrap.js" ]
Generate New Componentng g c ui/header <app-header></app-header>ng g c ui/footer <app-footer></app-footer>ng g c ui/navbar <app-navbar></app-navbar>ng g c ui/categoryng g c ui/home
Angular Routing
app-routing.ts const routes: Routes = [ {path:'', component:HomeComponent}, {path:'news', component:NewsComponent}];
header.component.ts<li class="nav-item"> <a class="nav-link" href="#" routerLink="/news" >ขาวประชาสัมพันธ</a></li>
Template Syntaximport { FormsModule } from '@angular/forms';
imports: [ ... FormsModule],
<input type="text" [(ngModel)]="categoryName"> <button (click)="categoryName='Default Category'">New</button>{{categoryName}}
Using Directives like ngFor and ngIfexport class AppComponent { title = 'ngApp'; categoryName = 'new'; categories = ['sport', 'technology'];
addNewCategory(){ this.categories.push(this.categoryName); }}
<div *ngIf="isActive"> <input type="text" [(ngModel)]="categoryName"> <button (click)="addNewCategory()">New</button></div>
<ul> <li *ngFor="let cat of categories"> {{cat}} </li></ul>
-------------------------------------------------<app-item></app-item>
Custom Properties and Event Bindingng g c item
app.component.html<h4 class="mt-3">All categories</h4><app-item *ngFor="let cat of categories" [catName]="cat"></app-item>
item.component.html<article class="cat"> <h4> {{catName}} </h4> <p>This is category detail.</p></article>
item.component.ts
import { Component, OnInit, Input } from '@angular/core';@Component({ selector: 'app-item', templateUrl: './item.component.html', styleUrls: ['./item.component.css']})export class ItemComponent implements OnInit { @Input() catName:string; constructor() { } ngOnInit() { }}
Custom Properties and Event Bindingitem.component.html<article class="cat"> <h4> {{catName}} <small (click)="onClicked()"> Delete</small></h4> <p>This is category detail.</p></article>
app.component.html <app-item *ngFor="let cat of categories" [catName]="cat" (catClicked)="removeCat(cat)"> </app-item>
item.component.ts
import { Component, OnInit, Input, EventEmitter, Output } from '@angular/core';@Component({ selector: 'app-item', templateUrl: './item.component.html', styleUrls: ['./item.component.css']})export class ItemComponent implements OnInit { @Input() catName:string; @Output() catClicked = new EventEmitter(); constructor() { } onClicked() {
this.catClicked.emit(); }}
Custom Properties and Event Bindingapp.component.ts removeCat(catName:string){ this.categories=this.categories.filter(p=>p!== catName); }
Router Navigate<a (btnClicked)="onBtnClicked('/parent/detail/123')">
onBtnClicked(url) { this.router.navigate(url);}
Formsapp.component.html <form (ngSubmit)="addNewCategory(f)" #f="ngForm"> <input type="text" ngModel name="categoryName" required> <button type="submit">New</button> </form>
app.component.tsaddNewCategory(form:any){ console.log(form); if(form.valid){ this.categories.push(form.value.categoryName); } }
Servicesng g s category
category.service.ts
export class CategoryService { private categories = ['sport', 'bitcoin']; constructor() { }
addCategory(categoryName:string){ this.categories.push(categoryName); }
getCategory(){ return [...this.categories]; } }
app.module.ts import { CategoryService } from './category.service';providers: [CategoryService],
category.component.ts
import { CategoryService } from 'src/app/category.service';constructor(public categoryService:CategoryService) { this.categories = this.categoryService.getCategory();}
addNewCategory(form:any){ if(form.valid){ this.categoryService.addCategory(form.value.categoryName); }}
Servicescategory.service.ts
import { Subject } from 'rxjs';export class CategoryService { categoryUpdated = new Subject(); addCategory(categoryName:string){ this.categories.push(categoryName); this.categoryUpdated.next(); }}
category.component.ts import { Subscription } from 'rxjs';export class CategoryComponent implements OnInit, OnDestroy {private categorySubscription:Subscription;
ngOnInit() { this.categories = this.categoryService.getCategory(); this.categorySubscription = this.categoryService.categoryUpdated.subscribe(()=>{ this.categories = this.categoryService.getCategory(); });}
ngOnDestroy(){ this.categorySubscription.unsubscribe();}
}
Services
category.service.ts
deleteCategory(categoryName:string){ this.categories = this.categories.filter(p=>p!==categoryName); this.categoryUpdated.next();}
item.component.ts import { CategoryService } from 'src/app/category.service';constructor(public categoryService:CategoryService){ }
onClicked(){ this.categoryService.deleteCategory(this.catName);}
BackendAPI with Laravelcomposer create-project --prefer-dist laravel/laravel backendAPI
Create MySql DB and Import table
Config DB connect in .env file
php artisan make:model Categories
php artisan serve
Group Middleware
Route::middleware(['cors'])->group(function () { Route::get('/info', function () { return response()->json([ 'name' => 'News API', 'version' => '1.0.1', 'updated' => '21/Jun/2016' ]); });});
Call REST APIapp.module.ts
import { HttpClientModule } from '@angular/common/http';imports: [ …., HttpClientModule ],
category.service.ts
import { HttpClient } from '@angular/common/http';constructor(public http:HttpClient) { }
category.component.ts
getData(){this.http.get('http://localhost:8000/api/category').subscribe(result=>{ this.categories=result; }); }
App/Http/Middleware/Core.phppublic function handle($request, Closure $next){ header('Access-Control-Allow-Origin: *'); header('Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS'); header('Access-Control-Allow-Headers: Content-Type, Accept, Authorization, X-Requested-With, Application'); return $next($request); }
App\Http\Kernel.php:protected $middlewareGroups = [ 'api' => [
... \App\Http\Middleware\Cors::class
],];
php artisan make:middleware Cors
URL ParametersRoutes{ path: "animals/:animal", component: AnimalsComponent }
Accessing the urlimport { ActivatedRoute } from "@angular/router";constructor(private route: ActivatedRoute) { }
Accessing url parametersnews:any;category:string='sport';constructor(public http:HttpClient, private route: ActivatedRoute) { this.getData(this.category);}ngOnInit() { this.route.paramMap.subscribe(params => { this.animal = params.get("animal"); })}
URL ParametersGetData from REST API
getData(category:string){ this.http.get<any>('https://newsapi.org/v2/top-headlines?country=th&category='+category+'&apiKey=176ab3b50a584b7bb4c825bc236f6b32').subscribe(result=>{ this.news=result.articles; console.log(result.articles); }); }
Angular, Firebase
Firebase is a Backend-as-a-Service — BaaS — startup and grew up into a next-generation app-development platform on Google Cloud Platform.
What’s Firebase
Firebase
Backend as a Service
Mobile Backend as a Service
Mobile Backend as a Service
Getting start with Firebase
Create new project
Project Console
What is Angularfire : Datastream
Firebase
Angular App
AngularfireSDKREST APIRXJS
ObservablesRefresher
Diving into Firebase- Create database in Cloud Firestore
Cloud Firestore Data modelhttps://firebase.google.com/docs/firestore/data-model
Add New Collection Generate Auto-ID
Diving into Firebase
Angularfire installation- https://github.com/angular/angularfire2 - go to “Installation and Setup” Angularfire
- npm install firebase @angular/fire --save
- Add Firebase config to environments variable in /src/environments/environment.ts
Setup Angularfire
Setup @NgModule for the AngularFireModuleimport { AngularFireModule } from '@angular/fire';import { environment } from '../environments/environment';import { AngularFirestoreModule } from '@angular/fire/firestore';
@NgModule({ imports: [ BrowserModule, AngularFirestoreModule, AngularFireModule.initializeApp(environment.firebase) ], declarations: [ AppComponent ], bootstrap: [ AppComponent ]})export class AppModule {}
Operators and RxJS6
Update file category.component.ts
import { AngularFirestore } from '@angular/fire/firestore';…..export class WelcomeComponent implements OnInit { constructor(private db: AngularFirestore) { this.getData(); }
getData() { this.categorySubscription = this.db.collection('categories').valueChanges().subscribe(result=>{ this.categories=result; }); }}
Storing Completed on Firestore addNewCategory(form:any){ if(form.valid){ this.db.collection('categories').add({ name: form.value.categoryName, detail: 'this is detail' }); } }
Authenthication on Firestore
- onLogin(form:NgForm){ console.log(form); this.afAuth.auth.signInWithEmailAndPassword(form.value.email, form.value.password).then(result=>{ console.log(result); }).catch(error => { alert(error.message); });
}
- authSuccess(){ this.authChange.next(true); this.router.navigate(['/training']); }
- logout(){ this.user = null; this.authChange.next(false); this.router.navigate(['/login']); }
- onSubmit(form:NgForm){ console.log(form); //alert(form.value.email); this.afAuth.auth.createUserWithEmailAndPassword(form.value.email, form.value.password).then(result=>{ console.log(result); }).catch(error => { alert(error.message); }); }
- authChange = new Subject<boolean>();constructor(private afAuth: AngularFireAuth, private router:Router) { }
Deploying the App- Preparation
- ng build --prod
- Deploying the App to Firebase Hosting- npm install -g firebase tools- firebase login - firebase init- firebase deploy
Reviewshttps://angular-templates.io/tutorials/about/angular-crud-with-firebase