Ionic angular won't send headers - javascript

I am trying to store data in database with API and I'm getting Trying to get property 'id' of non-object error.
The reason that I'm getting that error is because Ionic won't send my user token to server
0: Closure (HttpHeaders)
headers:
Accept: "application/json, text/plain"
Authorization: "undefined undefined" <--- here
Content-Type: "application/json"
Code
store.page.ts
This data will send to store services and from there to the server.
create() {
const addToko = this.addToko.value;
this.storeService.store(
addToko.name,
addToko.description,
addToko.phone,
addToko.province_id,
addToko.kota_id,
addToko.address,
addToko.logo = this.logoURI,
addToko.banner = this.bannerURI,
).subscribe(
data => {
this.alertService.presentToast(data);
console.log('done ', data);
},
error => {
this.alertService.presentToast(error);
console.log('error ', error);
}
);
}
store.service.ts
Data from here will send to server
export class StoreService {
token: any; //setting user token
constructor(
private http: HttpClient,
private env: EnvService,
private storage: NativeStorage,
) {
//gettinguser token
this.storage.getItem('token').then(
data => {
this.token = data;
console.log('token data', data);
},
error => {
this.token = null;
}
);
}
store(
name: String,
description: String,
phone: String,
province_id: String,
kota_id: String,
address: String,
logo: String,
banner: String,
) {
// adding headers to request
const headers = new HttpHeaders({
'Accept': 'application/json, text/plain',
'Content-Type': 'application/json',
'Authorization': this.token["token_type"] + " " + this.token["access_token"]
});
return this.http.post(this.env.STORES_URL,
{ name: name, description: description, phone: phone, province_id: province_id, kota_id: kota_id, address: address, logo: logo, banner: banner, headers: headers } // defining headers to request
)
}
}
Might be a bit of help:
I have Auth.service.ts which takes care of user loggin status and route guards etc. there I have function below which gets users token and in there it's working just fine, I implemented same function in my store.service.ts (code above) but it doesn't work.
getToken() {
return this.storage.getItem('token').then(
data => {
this.token = data;
if (this.token != null) {
this.isLoggedIn = true;
} else {
this.isLoggedIn = false;
}
},
error => {
this.token = null;
this.isLoggedIn = false;
}
);
}
Any idea?

your implemenation of store service needs a correction.
You've included the headers in object body, take it out from there.
return this.http.post(this.env.STORES_URL,
{ name: name, description: description, phone: phone, province_id:
province_id, kota_id: kota_id, address: address, logo: logo,
banner: banner, headers: headers /* headers should not be embedded in object body*/
});
return this.http.post(this.env.STORES_URL,
{ name: name, description: description, phone: phone, province_id:
province_id, kota_id: kota_id, address: address, logo: logo,
banner: banner
}, {headers: headers});

This is probably a race condition, the token has not been set before making the request. You could make a http-interceptor to take care of setting the auth header to your requests:
import { Injectable } from '#angular/core';
import {
HttpEvent, HttpInterceptor, HttpHandler, HttpRequest
} from '#angular/common/http';
import { Observable } from 'rxjs';
import { of, from} from 'rxjs';
import { switchMap, tap } from 'rxjs/operators';
#Injectable()
export class NoopInterceptor implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler):
Observable<HttpEvent<any>> {
// convert promise to observable
// fetch token and switch to inner observable where we add headers
return from(this.storage.getItem('token')).pipe(
switchMap((token) => {
// clone request and add headers
const authReq = req.clone({
headers: new HttpHeaders({
'Authorization': token["token_type"] + " " + token["access_token"]
})
})
return next.handle(authReq);
})
)
}
Add the interceptor to providers array in app.module:
{ provide: HTTP_INTERCEPTORS, useClass: NoopInterceptor, multi: true },
Then just remove the httpOptions from your request (which was like in other answer, in the wrong place):
return this.http.post(this.env.STORES_URL,
{ name: name, description: description, phone: phone, province_id:
province_id, kota_id: kota_id, address: address, logo: logo,
banner: banner
});

Related

How to get status code in angular observable

I have services below that I'd like to get status code and handle if statements in it but so far I couldn't figure it out
import { Injectable } from '#angular/core';
import { EnvService } from './env.service';
import { tap } from 'rxjs/operators';
import { Observable, from } from 'rxjs';
import { map, switchMap } from 'rxjs/operators';
import { HttpClient, HttpHeaders } from '#angular/common/http';
import { NativeStorage } from '#ionic-native/native-storage/ngx';
import { Plugins } from '#capacitor/core';
const { Storage } = Plugins;
#Injectable({
providedIn: 'root'
})
export class InvoicesServiceService {
token: any;
constructor(
private env: EnvService,
private http: HttpClient,
private nativeStorage: NativeStorage
) {
Storage.get({ key: 'token' }).then((token: any) => {
this.token = JSON.parse(token.value)
}).catch(error => console.error(error));
}
// All
getInvoices(): Observable<any> {
const tokenPromise =
this.token === undefined
? Storage.get({ key: 'token' })
: Promise.resolve(this.token);
return from(tokenPromise).pipe(
switchMap((token) => {
this.token = this.token;
const httpOptions = {
headers: new HttpHeaders({
Accept: 'application/json, text/plain',
'Content-Type': 'application/json',
Authorization: this.token.access_token,
}),
};
return this.http
.get(`${this.env.Dashboard}` + '/invoices', httpOptions)
.pipe(map((data) => data));
})
);
}
What I try to do is that if, status code is 403 redirect user to specific route other than that just return data.
any idea?
In component where you subscribe this service you can handle error
this.service
.getInvoices()
.subscribe((response) => {
// This is success
},
(error: HttpErrorResponse) => {
// Handle error
// Use if conditions to check error code, this depends on your api, how it sends error messages
});
Another way to handle in service itself.
return this.http
.get(`${this.env.Dashboard}` + '/invoices', httpOptions)
.pipe(map((data) => data))
.toPromise()
.then((response) => {
//Success
})
.catch((error: HttpErrorResponse) => {
// Handle error
});
Hope this helps.
The error is not always sent in the headers.
Sometimes the erros comes via HTML message, like when NGINX tells you someting before you even get to the backend:
<html>
<head><title>413 Request Entity Too Large</title></head>
<body>
<center><h1>413 Request Entity Too Large</h1></center>
<hr><center>nginx</center>
</body>
</html>
In these cases you should use if (error.includes('413 Request Entity Too Large')) {...}

Angular observable return undefined results

I have service which i pass user token to server and return results to component but it keeps returning token: undefined while my token is exist.
Code
Note: I commented each part for better understanding.
Service
export class GroupsService {
token: any;
constructor(
private storageIonic: NativeStorage,
private env: EnvService,
private http: HttpClient,
) {
// Get token
this.storageIonic.getItem('token').then((token) => {
this.token = token.access_token;
}).catch(error => console.error(error));
}
getGroups(): Observable<any> {
// I also add this here to make sure that i will get token in any case, yet it's returning undefined
if (this.token === undefined) {
this.storageIonic.getItem('token').then((token) => {
this.token = token.access_token;
}).catch(error => console.error(error));
}
console.log('token: ', this.token); // undefined
const httpOptions = {
headers: new HttpHeaders({
Authorization : this.token, //sending token to server
Accept: 'application/json, text/plain',
'Content-Type': 'application/json'
})
};
return this.http.get(`${this.env.GROUPS}`, httpOptions).pipe(
map(groups => groups)
);
}
}
Component
export class Tab1Page implements OnInit {
groups: any[] = [];
groupsOpts = {
loop: false,
slidesPerView: 3,
slidesPerColumn: 2
};
constructor(
private groupsService: GroupsService,
private menu: MenuController,
) {
this.menu.enable(true);
this.getGroups();
}
ngOnInit() {
//
}
// I added async/await yet result hasn't change.
async getGroups() {
await this.groupsService.getGroups().subscribe((res) => {
console.log('res: ', res);
console.log('res data: ', res.data);
console.log('res data data: ', res.data.data);
for (const group of res.data) {
this.groups.push(group);
}
});
}
}
Any idea how to solve this issue?
You can use switchMap to pipe the token promise data.
import { from } from "rxjs";
export class GroupsService {
token: any;
getGroups(): Observable<any> {
// I also add this here to make sure that i will get token in any case, yet it's returning undefined
const tokenPromise =
this.token === undefined
? this.storageIonic.getItem("token")
: Promise.resolve(this.token);
return from(tokenPromise).pipe(
switchMap((token) => {
this.token = token;
const httpOptions = {
headers: new HttpHeaders({
Authorization: this.token, //sending token to server
Accept: "application/json, text/plain",
"Content-Type": "application/json",
}),
};
return this.http
.get(`${this.env.GROUPS}`, httpOptions)
.pipe(map((groups) => groups));
})
);
}
}
You need to wait for the promise to return a value before making the http request. You could put your token logic into its own function that returns a promise, and then start an observable using the RxJS from function. Once the promise returns a value you can then use switchMap to make your http request.
I have included your map in the RxJS pipe, although it's doing nothing at the moment.
export class GroupsService {
token: any;
constructor(
private storageIonic: NativeStorage,
private env: EnvService,
private http: HttpClient,
) {
}
getGroups(): Observable<any> {
return from(this.getToken()).pipe(
switchMap(() => {
const httpOptions = {
headers: new HttpHeaders({
Authorization : this.token, //sending token to server
Accept: 'application/json, text/plain',
'Content-Type': 'application/json'
})
};
return this.http.get(`${this.env.GROUPS}`, httpOptions);
}),
map(groups => groups)
);
}
private getToken(): Promise<any> {
if (this.token) {
return new Promise((resolve, reject) => resolve(this.token));
}
return this.storageIonic.getItem('token')
.then((token) => {
this.token = token.access_token;
}).catch(error => console.error(error));
}
}
this.storageIonic.getItem('token').then((token) => {
this.token = token.access_token;
}).catch(error => console.error(error));
}
This call is asychronous, you will not get the token in the next line
Try it out like this
export class GroupsService {
token: any;
constructor(
private storageIonic: NativeStorage,
private env: EnvService,
private http: HttpClient,
) {
// Get token
this.storageIonic.getItem('token').then((token) => {
this.token = token.access_token;
}).catch(error => console.error(error));
}
getGroups(): Observable < any > {
// I also add this here to make sure that i will get token in any case, yet it's returning undefined
let response = new Observable<any>();
if (this.token === undefined) {
this.storageIonic.getItem('token').then((token) => {
this.token = token.access_token;
console.log('token: ', this.token); // undefined
const httpOptions = {
headers: new HttpHeaders({
Authorization: this.token, //sending token to server
Accept: 'application/json, text/plain',
'Content-Type': 'application/json'
})
};
response = this.http.get(`${this.env.GROUPS}`, httpOptions).pipe(
map(groups => groups)
);
}).catch(error => console.error(error));
}
return response;
}
}
I am not sure about the source of your problem but you may want to change your observables to promises as I have explained in the comments.
getGroups(): Promise<any> {
// I also add this here to make sure that i will get token in any case, yet it's returning undefined
if (this.token === undefined) {
this.storageIonic.getItem('token').then((token) => {
this.token = token.access_token;
}).catch(error => console.error(error));
}
console.log('token: ', this.token); // undefined
const httpOptions = {
headers: new HttpHeaders({
Authorization : this.token, //sending token to server
Accept: 'application/json, text/plain',
'Content-Type': 'application/json'
})
};
return this.http.get(`${this.env.GROUPS}`, httpOptions).toPromise();
// Also probably the below one works too, you can try to find the proper syntax, it was something like this
return this.http.get(`${this.env.GROUPS}`, httpOptions).pipe(
map(groups => groups)
).toPromise();
}
I have changed some lines. (Change method signature, Observable => Promise and add toPromise() to return line)
You can call the method like below.
const response = await getGroups(); // This one will return the response of the request.
If you debug the code you will see that your code will wait here until it gets a response.
// IF YOU DO LIKE BELOW IT WON'T MAKE ANY SENSE
const response = getGroups(); // This will not make the call, it will just return the request object.
// In order to do the operation defined in a promise, you must call it with await prefix.
You may need apply the solution above to other parts of your code too. E.g. you are initializing the token under the constructor which it is not a good practice as I know, you may want to move that initialization under onInit() and make onInit function async. This way you can make sure that token is defined when you are making the call, otherwise your token may not beer initialized while you are making the request. And since you are not waiting your code in undefined check same thing will happen again.
(Convert your storageIonic.getItem(token: string) function to a promise and return the token from that function)

Angular 6: How to set response type as text while making http call

I trying to make http request to the spring rest API.. API returns a string value ("success" or "fail")... but I dont know how to set the response type as string value while making call to the API..its throwing error as Backend returned code 200, body was: [object Object]
My angular code is like below,
order.service.ts
import { Injectable } from '#angular/core';
import { HttpClient, HttpHeaders } from '#angular/common/http';
import { ProductSearch } from '../_models/product-search';
import { ProductView } from '../_models/product-view';
import { Observable } from 'rxjs';
import { catchError } from 'rxjs/operators';
import { ErrorHandlerService } from './error-handler.service';
import { Category } from '../_models/category';
#Injectable({
providedIn: 'root'
})
export class OrderService {
constructor(private http: HttpClient, private errorHandlerService: ErrorHandlerService) { }
addToCart(productId: number, quantity: number): Observable<any> {
const headers = new HttpHeaders().set('Content-Type', 'text/plain; charset=utf-8');
console.log("--------order.service.ts----------addToCart()-------productId:"+productId+":------quantity:"+quantity);
return this.http.post<any>('http://localhost:8080/order/addtocart',
{ dealerId: 13, createdBy: "-1", productId: productId, quantity: quantity},
{headers: headers})
.pipe(catchError(this.errorHandlerService.handleError));
}
}
error-handler.service.ts
import { Injectable } from '#angular/core';
import { HttpErrorResponse, HttpResponse } from '#angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError, retry } from 'rxjs/operators';
#Injectable({
providedIn: 'root'
})
export class ErrorHandlerService {
constructor() { }
public handleError(error: HttpErrorResponse) {
if (error.error instanceof ErrorEvent) {
// A client-side or network error occurred. Handle it accordingly.
console.error('An error occurred:', error.error.message);
} else {
// The backend returned an unsuccessful response code.
// The response body may contain clues as to what went wrong,
console.error(
`Backend returned code ${error.status}, ` +
`body was: ${error.error}`);
}
// return an observable with a user-facing error message
return throwError(
'Something bad happened; please try again later.');
};
}
You should not use those headers, the headers determine what kind of type you are sending, and you are clearly sending an object, which means, JSON.
Instead you should set the option responseType to text:
addToCart(productId: number, quantity: number): Observable<any> {
const headers = new HttpHeaders().set('Content-Type', 'text/plain; charset=utf-8');
return this.http.post(
'http://localhost:8080/order/addtocart',
{ dealerId: 13, createdBy: "-1", productId, quantity },
{ headers, responseType: 'text'}
).pipe(catchError(this.errorHandlerService.handleError));
}
To get rid of error:
Type '"text"' is not assignable to type '"json"'.
Read the Angular HTTP guide and use
responseType: 'text' as const
import { HttpClient, HttpHeaders } from '#angular/common/http';
.....
return this.http
.post<string>(
this.baseUrl + '/Tickets/getTicket',
JSON.stringify(value),
{ headers, responseType: 'text' as const }
)
.map(res => {
return res;
})
.catch(this.handleError);
On your backEnd, you should add:
#RequestMapping(value="/blabla", produces="text/plain" , method = RequestMethod.GET)
On the frontEnd (Service):
methodBlabla()
{
const headers = new HttpHeaders().set('Content-Type', 'text/plain; charset=utf-8');
return this.http.get(this.url,{ headers, responseType: 'text'});
}
Use like below:
yourFunc(input: any):Observable<string> {
var requestHeader = { headers: new HttpHeaders({ 'Content-Type': 'text/plain', 'No-Auth': 'False' })};
const headers = new HttpHeaders().set('Content-Type', 'text/plain; charset=utf-8');
return this.http.post<string>(this.yourBaseApi+ '/do-api', input, { headers, responseType: 'text' as 'json' });
}
For me this way worked. Like requestOptions as object
returnObservable(): Observable<any> {
const headers = new HttpHeaders().set('Content-Type', 'text/plain; charset=utf-8');
const requestOptions: Object = {
headers: headers,
responseType: 'text'
}
return this.http.get<any>(this.streamURL , requestOptions);
}
To fix the compiler error, remove the generic type argument from the post method call.
DO THIS
return this.http.post('example', postBody, {
responseType: 'text'
});
NOT THIS
return this.http.post<any>('example', postBody, {
responseType: 'text'
});
The error appears because the post method signature does not contain a generic type argument when responseType: 'text.
See the different method signatures below:
With responseType: 'json' (the default)
post<T>(url: string, body: any | null, options?: {
...
responseType?: 'json';
...
}): Observable<T>;
With responseType: 'text'
post(url: string, body: any | null, options: {
...
responseType: 'text';
...
}): Observable<string>;
Notice the generic type argument only exists for type 'json'.
Remove it to fix the error.
The default assumption of the HttpClient is 'json' responseType.
If you want to change it to 'text', you should do it like so:
public signIn(dto: UserCredentialsDto): Promise<string> {
return this.http.post<string>(
`${this.url}/userCredentials/signIn`, dto, { responseType: 'text' as 'json'}).toPromise();
}
By Default angular return responseType as Json, but we can configure below types according to your requirement.
responseType: 'arraybuffer'|'blob'|'json'|'text'
Ex:
this.http.post(
'http://localhost:8080/order/addtocart',
{ dealerId: 13, createdBy: "-1", productId, quantity },
{ headers, responseType: 'text'});
Have you tried not setting the responseType and just type casting the response?
This is what worked for me:
/**
* Client for consuming recordings HTTP API endpoint.
*/
#Injectable({
providedIn: 'root'
})
export class DownloadUrlClientService {
private _log = Log.create('DownloadUrlClientService');
constructor(
private _http: HttpClient,
) {}
private async _getUrl(url: string): Promise<string> {
const httpOptions = {headers: new HttpHeaders({'auth': 'false'})};
// const httpOptions = {headers: new HttpHeaders({'auth': 'false'}), responseType: 'text'};
const res = await (this._http.get(url, httpOptions) as Observable<string>).toPromise();
// const res = await (this._http.get(url, httpOptions)).toPromise();
return res;
}
}

Working with HTTP-responses in angular2

I'm working on web-app with authorization via JWT and Angular 2. I've Nodejs/express server with API and client-side on Angular2.
So, my server answers GET request correctly and gives data like this:
{
"success": true,
"user": {
"_id": "5a6ef70edb04dd29e24bb03b",
"email": "danko",
"username": "ivan"
}
}
Next, here is my auth.service.ts. Functions createAuthenticationHeaders() and getProfile() takes part in handling HTTP responses:
import { Injectable } from '#angular/core';
import { HttpClient, HttpHeaders, HttpRequest, HttpResponse, HttpParams} from '#angular/common/http';
import { Http, Headers, RequestOptions} from '#angular/http'; // Http, Headers, RequestOptions
import 'rxjs/add/operator/map';
#Injectable()
export class AuthService {
domain = "http://localhost:8080";
authToken;
user;
options;
constructor(
private http: HttpClient,
private httplegacy: Http) { }
createAuthenticationHeaders() {
this.loadToken();
this.options = new RequestOptions({
headers : new Headers({
'Content-Type' : 'application/json',
'authorization' : this.authToken
})
});
}
loadToken() {
this.authToken = localStorage.getItem('token');
}
registerUser(user) {
return this.http.post(this.domain + '/authentication/register', user);
}
loginUser(user) {
return this.http.post(this.domain + '/authentication/login', user);
}
storeUserData(token, user) {
localStorage.setItem('token', token);
localStorage.setItem('user', JSON.stringify(user));
this.authToken = token;
this.user = user;
}
getProfile() {
this.createAuthenticationHeaders();
return this.httplegacy.get(this.domain + '/authentication/profile', this.options);
}
}
Also, here is my profile.component.ts:
import { Component, OnInit } from '#angular/core';
import { AuthService} from '../../services/auth.service';
#Component({
selector: 'app-profile',
templateUrl: './profile.component.html',
styleUrls: ['./profile.component.css']
})
export class ProfileComponent implements OnInit {
username;
email;
constructor(
private authService: AuthService
) { }
ngOnInit() {
this.authService.getProfile().subscribe(profile => {
console.log(profile);
this.username = profile.user.username;
this.email = profile.user.email;
})
}
}
Expected behavior of these lines of code: after handling server's response with user's data with auth.service.ts(mainly createAuthenticationHeaders() and getProfile() functions), user's data is transmitted to profile.component.ts to show it on web-page using next code:
<h2 class="page-header">Profile Page</h2>
<ul class="list-group">
<li class="list-group-item">Username: {{ username }} </li>
<li class="list-group-item">Email: {{ email }}</li>
</ul>
But, while compiling I got an error: property 'user', doesn't exist on type 'Response'. Would You like to explain why i got such error, and how to fix it?
P.S.: yep, console.log(profile) gives me such info:
Response {_body: "{"success":true,"user":{"_id":"5a6ef70edb04dd29e24bb03b","email":"danko","username":"ivan"}}", status: 200, ok: true, statusText: "OK", headers: Headers, …}
headers:Headers {_headers: Map(1), _normalizedNames: Map(1)}
ok : true
status : 200
statusText : "OK"
type : 2
url : "http://localhost:8080/authentication/profile"
_body : "{"success":true,"user":{"_id":"5a6ef70edb04dd29e24bb03b","email":"danko","username":"ivan"}}"
__proto__ : Body
constructor : ƒ Response(responseOptions)
toString : ƒ ()
__proto__ :
Object
But how can I get data from _body field of response?
P.S.: code for router from server side:
router.get('/profile', (req, res) => {
User.findOne({ _id: req.decoded.userId }).select('username email').exec((err, user) => {
if (err) {
res.json({ success: false, message: err });
} else {
if(!user) {
res.json({ success: false, message: 'User not found'});
} else{
res.json({ success: true, user: user });
}
}
});
});
you try to read your data directly from the Response Object of express. You need smth like:
this.authService.getProfile().subscribe(profile => {
console.log(profile);
let p = JSON.parse(profile._body)
this.username = p.user.username;
this.email = p.user.email;
})
This will take the JSON string from the body of your HTTP Response and make it an accessible object.
NOTE:
It would be much better to tell the server to answer with a standard json due to this is web standard nowadays.
Update: #messerbill's was 50/50 correct. Such construction works:
this.authService.getProfile().subscribe(profile => {
console.log(profile);
let p = JSON.parse(profile._body)
this.username = p.user.username;
this.email = p.user.email;
})
My web-page got user's info and show it in correctly, but an error left and i've to comment these lines of code to compile and run my application, and uncomment after to see user's info on webpage.
An error message: property '_body' does not exists on type 'Response'.
So, at this moment i've no idea how it works with an error and how to create really correct structure.
Try this
ngOnInit() {
this.authService.getProfile().subscribe(profile => {
console.log(profile);
let p = profile.json();
this.username = p.user.username;
this.email = p.user.email;
})
}

Angular 4 with mailgun

I am trying to make a simple email form for one of my websites that allows people to contact me. This site is using angular 4, and mailgun as the mail service. In my mail service file I have this method that sends the message, but I am getting a Bad Request error saying from is not present.
public sendMail(){
let url = 'https://api.mailgun.net/v3/XXXXXXXXXXXX.mailgun.org/messages';
let headers: Headers = new Headers();
headers.append('Authorization','Basic '+ btoa('api:key-XXXXXXXXXXXXXXXXXXX'));
headers.append("Content-Type", "application/x-www-form-urlencoded");
let opts: RequestOptions = new RequestOptions();
opts.headers = headers;
this.http.post(url,
{
from: '"Mailgun Sandbox" <postmaster#XXXXXXXXXX.mailgun.org>',
to: "Test <test#gmail.com>",
subject: 'Hello ',
text: 'Congratulations, you just sent an email with Mailgun! You are truly awesome!'
},
opts
).subscribe(
success => {
console.log("SUCCESS -> " + JSON.stringify(success));
}, error => {
console.log("ERROR -> " + JSON.stringify(error));
}
);
}
I am having a hard time understanding why from is showing up not as present when I send the request. Any help is great.
import { Injectable } from '#angular/core';
import { HttpHeaders, HttpClient } from '#angular/common/http';
#Injectable({
providedIn: 'root'
})
export class PostService {
constructor(private http: HttpClient) {
}
sendMail() {
const headers = new HttpHeaders({
'enctype': 'multipart/form-data',
'Authorization': 'Basic ' + btoa('api:xxxxxxxxxxxxxxxxxxxxxxxxxx-xxxxxx-xxxxxx')
});
const formData = new FormData();
formData.append('from', 'Mailgun Sandbox <postmaster#sandboxxxxxxxxxxxxxx.mailgun.org>');
formData.append('to', 'xxxxxxxxxxxxxx.com');
formData.append('subject', 'Hello');
formData.append('text', 'This is cool !');
this.http
.post(
'https://api.mailgun.net/v3/sandboxxxxxxxxxxxxxxxxxxxxxxxxxxb.mailgun.org/messages',
formData,
{ headers }
).subscribe(
res => { console.log('res : ', res); },
err => { console.log('err : ', err); }
);
}
}

Categories

Resources