error TS2559: Type 'Headers' has no properties in common with type 'RequestOptionsArgs'

折月煮酒 提交于 2019-12-24 00:38:47

问题


This is my code but, I'm getting the same result. how can I fix this for it to work?

error TS2559: Type 'Headers' has no properties in common with type '{ headers?: HttpHeaders | { [header: string]: string | string[]; }; observe?: "body"; params?: 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:


As you are using the new HttpClientfrom '@angular/common/http'; (introduced in Angular 4) along with the HttpClientModule to make the POST call, hence you should use HttpHeaders instead of Headers from '@angular/http'; . You also need to pass the the headers as an Object like {headers}.

Here is the modified code -

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

  }


来源:https://stackoverflow.com/questions/51224476/error-ts2559-type-headers-has-no-properties-in-common-with-type-requestoptio

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!