2016-09-17 132 views
2

我想嵌入一個mailchimp註冊表單到我的angular2應用程序。Mailchimp註冊表單與angular2

http://kb.mailchimp.com/lists/signup-forms/add-a-signup-form-to-your-website

我被困在做一個HTTP POST調用mailchimp服務器。我在這裏引用angular2指南:https://angular.io/docs/ts/latest/guide/server-communication.html

這是我在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); 
    } 

據我所知,瀏覽器會因CORS引發錯誤。我曾嘗試使用Chrome擴展插件來嘗試並測試http調用是否正常。它拋出這個錯誤。

XMLHttpRequest cannot load http://us14.list-manage.com/subscribe/post?u=xxxxxxxxxxxxxxxxxx&amp;id=xxxxxxxxxxxxxxxxx. Response for preflight has invalid HTTP status code 501 

不知道我是否在做錯事。問題是無論如何,我可以使它工作,而無需創建一個服務器端調用到mailchimp服務器?謝謝。

回答

2

你應該能夠JSONP請求來實現:

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

請求應作出別的其他地方不是組件(例如,服務)的構造,但對於一個快速和骯髒的例子的緣故。

注:這是未經測試的代碼轉換爲from an example using an older version of Angular 2,但這個概念應該仍然有效。

+1

謝謝@Steve。 我後來發現了另一個類似的問題。 [鏈接](http://stackoverflow.com/questions/35180562/i-need-to-do-a-http-request-to-a-mail-chimp-subscription-list-via-a-component-po/ 35181085#35181085) –

+0

感謝您的跟進,@slvndev!我已經把這個問題標記爲重複http://stackoverflow.com/questions/35180562/i-need-to-do-a-http-request-to-a-mail-chimp-subscription-list-via- a-component-po/35181085#35181085將這兩個問題聯繫在一起。希望這會使未來更容易找到答案。 –