这是我的代码,但是得到的结果相同。我该如何解决这个问题?
错误import { Component, OnInit } from '@angular/core';
import { Http, Headers, Response, URLSearchParams } from '@angular/http';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import 'rxjs/add/operator/toPromise';
@Component({
selector: 'app-send-mail',
templateUrl: './send-mail.component.html',
styleUrls: ['./send-mail.component.css']
})
export class SendMailComponent implements OnInit {
constructor(private http: HttpClient) { }
sendEmail() {
const url = `https://your-cloud-function-url/function`;
const params: URLSearchParams = new URLSearchParams();
const headers = new Headers({'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*' });
params.set('to', 'email');
params.set('from', 'email@website.com');
params.set('subject', 'test-email');
params.set('content', 'Hello World');
return this.http.post(url, params, headers)
.toPromise()
.then( res => {
console.log(res);
})
.catch(err => {
console.log(err);
});
}
答案 0 :(得分:2)
由于您正在使用HttpClient
中的新'@angular/common/http';
(在Angular 4中引入)以及HttpClientModule
来进行POST调用,因此您应该使用
HttpHeaders
而非Headers
中的'@angular/http';
。您还需要将标头作为{headers}
之类的对象传递。
这是修改后的代码-
sendEmail() {
const url = `https://your-cloud-function-url/function`;
const params: URLSearchParams = new URLSearchParams();
const headers = new HttpHeaders({'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*' });
params.set('to', 'email');
params.set('from', 'email@website.com');
params.set('subject', 'test-email');
params.set('content', 'Hello World');
return this.http.post(url, params, {headers})
.toPromise()
.then( res => {
console.log(res);
})
.catch(err => {
console.log(err);
});
}