Reputation: 144
I create a cloud functions on Firebase and I'm trying to do a POST method on it. How am I supposed to trigger this function into an Angular component ?
Here is what I did:
const url = 'my-cloud-function-url';
const params: URLSearchParams = new URLSearchParams();
params.set('id', this.id);
this.http.post(url, params)
.toPromise()
.then(res => {
console.log(res);
})
.catch(err => {
console.log(err);
});
So this code is working but the POST method doesn't take arguments in parameters. I know that I could change the url to add the argument in it but I'm pretty sure this is dirty method.
Thanks for your help!
Upvotes: 2
Views: 4006
Reputation: 755
https://angular.io/tutorial/toh-pt6#enable-http-services
Briefly, create service which call http post/get function. And when a component needs data, it would use the service like below :
sms.service.ts
import {Injectable} from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import 'rxjs/add/operator/map';
const BASE_API_URL = 'http-url';
const httpOptions = {
headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};
@Injectable()
export class SmsService {
constructor(public http: HttpClient){}
sendSms(sms){
return this.http.post(BASE_API_URL+'/sms/send', JSON.stringify(sms), httpOptions);
}
}
common.container.ts
import {Component, OnInit} from '@angular/core';
import {SmsService} from '../../services/sms.service';
@Component({
selector: 'app-common',
styleUrls: ['common.container.css'],
templateUrl: 'common.container.html'
})
export class CommonContainerComponent {
public number;
public smsMessage;
constructor(public smsService: SmsService) {}
sendSms(number, message) {
const sms = {
receiver : number,
context : message
};
this.smsService.sendSms(sms).subscribe(
results => {
console.log('sendSms results : ', results);
},
error => {
console.log('sendSms error : ', error);
},
() => {
console.log('sendSms completed');
}
);
}
}
Upvotes: 6