错误TS2559:“标头”类型与“ RequestOptionsArgs”类型没有共同的属性

时间:2018-07-07 15:18:12

标签: angular typescript http-headers

这是我的代码,但是得到的结果相同。我该如何解决这个问题?

错误
TS2559:类型'Headers'与类型'{headers没有共同的属性:HttpHeaders | {[header:string]:字符串|串[]; };观察?参数?:Ht ...'。

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);
                    });

  }

1 个答案:

答案 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);
                    });

  }