I am trying to embed a mailchimp sign up form to my angular2 application.
http://kb.mailchimp.com/lists/signup-forms/add-a-signup-form-to-your-website
I am stuck at doing a http post call to mailchimp server. I am referencing the angular2 guide here: https://angular.io/docs/ts/latest/guide/server-communication.html
This is my code in the data.service.
private mailChimpUrl = 'http://us14.list-manage.com/subscribe/post?u=xxxxxxxxxxxxxxxxxx&id=xxxxxxxxxxxxxxxxx';
addSubscriber(): Observable<string> {
let body = JSON.stringify( { "EMAIL" : "[email protected]" } );
let headers = new Headers({'Content-Type': 'application/json'});
let options = new RequestOptions({headers: headers});
return this.http.post(this.mailChimpUrl, body, options)
.map(this.extractData)
.catch(this.handleError);
}
I understand that browser will throw an error because of CORS. I have tried to use a chrome extension plugin to try and test if the http call is working. It throws this error.
XMLHttpRequest cannot load http://us14.list-manage.com/subscribe/post?u=xxxxxxxxxxxxxxxxxx&id=xxxxxxxxxxxxxxxxx. Response for preflight has invalid HTTP status code 501
Not sure if I am doing things wrongly. Question will be is there anyway I can make it work without creating a server side call to the mailchimp server? Thanks.
You should be able to accomplish this with a jsonp request:
import {Component} from '@angular/core';
import {Jsonp} from '@angular/http';
@Component({
selector: 'my-app',
template: `
<div>
Result: {{result | json}}
</div>
`
})
export class AppComponent {
constructor(jsonp:Jsonp) {
var url = 'https://mysubscriptionlist.us10.list-manage.com/subscribe/post-json?u=b0c935d6f51c1f7aaf1edd8ff&id=9d740459d3&subscribe=Subscribe&[email protected]&c=JSONP_CALLBACK';
jsonp.request(url, { method: 'Get' })
.subscribe((res) => { this.result = res.json() });
}
}
Working Plnkr using an older version of ng2
The request should be made somewhere else other than the constructor of a component (eg. Service), but for a quick and dirty example's sake.
Note: This is untested code converted from an example using an older version of Angular 2, but the concept should still work.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With