类型"标题"没有与类型相同的属性" RequestOptionsArgs

时间:2018-03-30 17:56:18

标签: angular typescript

尝试实施headers

时出现以下错误

enter image description here

The type" Headers "has no properties in common with the type" RequestOptionsArgs "

我正在阅读,显然现在我们应该使用HttpHeaders但我无法避免错误地实现它



import { Component, OnInit } from '@angular/core';
import { Http, Headers, Response, URLSearchParams } from '@angular/http';
import 'rxjs/add/operator/toPromise';

@Component({
  selector: 'app-contacto',
  templateUrl: './contacto.component.html',
  styleUrls: ['./contacto.component.scss']
})
export class ContactoComponent implements OnInit {

  constructor(private http: Http ) { }

  ngOnInit() {
  }

  sendMessage(){
   
    let url = `https://your-cloud-function-url/function`
    let params: URLSearchParams = new URLSearchParams();
    let headers = new Headers({'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*' });

    params.set('to', 'user@example.com');
    params.set('from', 'you@yoursupercoolapp.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)
      })

  }

}




2 个答案:

答案 0 :(得分:2)

与此相关的答案很少。

Difference between HTTP and HTTPClient in angular 4?

Type 'Headers' has no properties in common with type 'RequestOptionsArgs'?

在您的情况下(4.3之前的角度版本),工作解决方案如下所示。

import {Headers, Http, RequestOptions} from "@angular/http";

...

let headers = new Headers({'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*' });
let options = new RequestOptions({headers: headers});

...

return this.http.post(url, params, options)

...

答案 1 :(得分:0)

根据the official docs

import { HttpHeaders } from '@angular/common/http';

const httpOptions = {
  headers: new HttpHeaders({
    'Content-Type': 'application/json',
    'Access-Control-Allow-Origin': '*'
  }
};

return this.http.post(url, params, httpOptions)
    ...

这仅适用于较新的HttpClient实现,您应该可以轻松切换到该实现。只需像这样导入它:

import { HttpClient, HttpErrorResponse } from '@angular/common/http';

并将构造函数的签名更改为:

constructor(private http: HttpClient) {}