Introduction
Prerequisite:
- Create a project in firebase
- Use a realtime database
- Setup the database in test mode so that we can directly use it
here we have created a simple from and we will send the form data to the fire base.
Requests are only send when we subscribe to the request
Simple HTML Form
<div class="container">
<div class="row">
<div class="col-xs-12 col-md-6 col-md-offset-3">
<form #postForm="ngForm" (ngSubmit)="onCreatePost(postForm.value)">
<div class="form-group">
<label for="title">Title</label>
<input type="text" class="form-control" id="title" required ngModel name="title" />
</div>
<div class="form-group">
<label for="content">Content</label>
<textarea class="form-control" id="content" required ngModel name="content"></textarea>
</div>
<button class="btn btn-primary" type="submit" [disabled]="!postForm.valid">
Send Post
</button>
</form>
</div>
</div>
<hr />
<div class="row">
<div class="col-xs-12 col-md-6 col-md-offset-3">
<button class="btn btn-primary" (click)="onFetchPosts()">
Fetch Posts
</button>
|
<button class="btn btn-danger" [disabled]="loadedPosts.length < 1" (click)="onClearPosts()">
Clear Posts
</button>
</div>
</div>
<div class="row">
<div class="col-xs-12 col-md-6 col-md-offset-3">
<p>No posts available!</p>
</div>
</div>
</div>
How to send a Post Request ?
here we can see we have made a post request with URL and the postData and then subscribed to that post method and log the response.
import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
loadedPosts = [];
constructor(private http: HttpClient) {}
ngOnInit() {}
onCreatePost(postData: { title: string; content: string }) {
// Send Http request
console.log(postData);
this.http.post('https://ngfirstproject-default-rtdb.asia-southeast1.firebasedatabase.app/posts.json',
postData
).subscribe( responseData=> {
console.log(responseData);
} )
}
onFetchPosts() {
// Send Http request
}
onClearPosts() {
// Send Http request
}
}