typescript Angular 4 RequestOption 对象不可分配给 post 方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/47894300/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 05:07:39  来源:igfitidea点击:

Angular 4 RequestOption object not assignable for post method

angulartypescriptionic-framework

提问by Umut Gür

I'm trouble with these codes, I created a header with following code block

我对这些代码有问题,我用以下代码块创建了一个标题

headers.append("Authorization",btoa(username+":"+password));

var requestOptions = new RequestOptions({headers:headers});

But if I try use this in a post method in that

但是如果我尝试在 post 方法中使用它

return this.http.post(url,JSON.stringify({username,password}),requestOptions)
    .map(res=>res.json())
    .map(res=>{
      if(res){
        localStorage.setItem("isLogged",res);
        this.loggedIn =true;
      }
      return res;
    });

I take this error message

我接受这个错误信息

Typescript Error
Argument of type 'RequestOptions' is not assignable to parameter of type '{ headers?: HttpHeaders | { [header: string]: string | string[]; }; observe?: "body"; params?: Ht...'. Types of property 'headers' are incompatible. Type 'Headers' is not assignable to type 'HttpHeaders | { [header: string]: string | string[]; }'. Type 'Headers' is not assignable to type '{ [header: string]: string | string[]; }'. Index signature is missing in type 'Headers'.

I tried change Header() to HttpHeader() but it didn't help. What is the problem?

我尝试将 Header() 更改为 HttpHeader() 但它没有帮助。问题是什么?

UPDATED

更新

I removed requestOptions object then I created headers from HttpHeaders()

我删除了 requestOptions 对象,然后我从 HttpHeaders() 创建了标头

let headers = new HttpHeaders();

and use this headers value in post method in that

并在 post 方法中使用这个 headers 值

return this.http.post(url,JSON.stringify({username,password}), { options: { headers: headers; } })
    .map(res=>res.json())
    .map(res=>{
      if(res){
        localStorage.setItem("isLogged",res);
        this.loggedIn =true;
      }
      return res;
    });

then get this error

然后得到这个错误

[ts]
Argument of type '{ options: { headers: HttpHeaders; }; }' is not assignable to parameter of type '{ headers?: HttpHeaders | { [header: string]: string | string[]; }; observe?: "body"; params?: Ht...'.
  Object literal may only specify known properties, and 'options' does not exist in type '{ headers?: HttpHeaders | { [header: string]: string | string[]; }; observe?: "body"; params?: Ht...'.

I also tried this

我也试过这个

return this.http.post(url,JSON.stringify({username,password}), { headers: headers })
    .map(res=>res.json())
    .map(res=>{
      if(res){
        localStorage.setItem("isLogged",res);
        this.loggedIn =true;
      }
      return res;
    });

then I got an error on first ".map"

然后我在第一个“.map”上遇到错误

[ts] Property 'map' does not exist on type 'Observable<Object>'.

采纳答案by bazzells

The RequestOptionsclass was to be used with the deprecated Httpmodule, and since you're getting this error I'd assume you're using the HttpClientmodule.

RequestOptions班是使用旧版使用的Http模块,既然你得到这个错误我会假设你正在使用的HttpClient的模块。

If you want to set headersthrough optionsas shown in your code, you can use something like this (simplified version of what is shown in the Angular docs):

如果要设置headers通过options如在你的代码,你可以使用像这样(简化什么在角所示版本文档):

request(url, { body }, { options: { headers?: HttpHeaders; } })

But, you can also set headersdirectly, without using options. That would look something like this:

但是,您也可以headers直接设置,而不使用选项。那看起来像这样:

    request(url, { body }, { headers?: HttpHeaders; } )

回答by Peter Kovacs

@angular/http is deprecated

@angular/http 已弃用

Use @angular/common/http instead

改用@angular/common/http

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

const httpOptions = {
     headers: new HttpHeaders({
     'Content-Type':  'application/json',
     'Authorization': 'my-auth-token'
    })
};


addHero (hero: Hero): Observable<Hero> {
     return this.http.post<Hero>(this.heroesUrl, hero, httpOptions)
     .pipe(
      catchError(this.handleError('addHero', hero))
    );
}

回答by Anis Mokeddes

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

private headers = new Headers({
    'Content-Type': 'application/json',
    'Authorization': localStorage.getItem('token')
  });
  private options = new RequestOptions({
    headers: this.headers
  });

private user: User;

constructor(private _http: Http) {}

getUserService() {
    return this._http.get(this.baseUrl + '/user', this.options)
      .map((response: Response) => response.json(),
      error => error.json('erreur dans lurl'));
  }

回答by Akhil Babu

In services

在服务中

In the simple way passing multiple arguments

以简单的方式传递多个参数

export interface Doctor {

       license1d1: number;
       firstname1: string;
       experience1: number;
       fee1: number;
       qualification1: string;
       lastname1: string;
       specialization1: string;    }






     getDoctorsBydepartment(Hosp: number, Dept: number): Observable<Doctor[]> {

           const url = 'http://192.168.75.15:8080/Booking/rest/List.do?' 
           ClinicID='+Hosp+'&DeptID='+Dept;
           return this.http.get<Doctor[]>(url).pipe()

        }