Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
MailChimp subscribe form with Angular 5 using jsonp
import { Component } from '@angular/core';
import { FormControl, Validators } from '@angular/forms';
import { HttpClient, HttpParams } from '@angular/common/http';
interface MailChimpResponse {
result: string;
msg: string;
}
@Component({
selector: 'email-subscribe-form',
templateUrl: './email-subscribe-form.component.html'
})
export class EmailSubscribeForm {
submitted = false;
mailChimpEndpoint = 'https://username.us6.list-manage.com/subscribe/post-json?u=abc123&id=123&';
error = '';
constructor(private http: HttpClient) { }
// reactive form components
emailControl = new FormControl('', [
Validators.required,
Validators.email,
]);
nameControl = new FormControl('', [
Validators.required
]);
submit() {
this.error = '';
if (this.emailControl.status === 'VALID' && this.nameControl.status === 'VALID') {
const params = new HttpParams()
.set('NAME', this.nameControl.value)
.set('EMAIL', this.emailControl.value)
.set('b_123abc123abc123abc123abc123abc123abc', ''); // hidden input name
const mailChimpUrl = this.mailChimpEndpoint + params.toString();
// 'c' refers to the jsonp callback param key. This is specific to Mailchimp
this.http.jsonp<MailChimpResponse>(mailChimpUrl, 'c').subscribe(response => {
if (response.result && response.result !== 'error') {
this.submitted = true;
}
else {
this.error = response.msg;
}
}, error => {
console.error(error);
this.error = 'Sorry, an error occurred.';
});
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.