【问题标题】:Angular 4 RequestOption object not assignable for post methodAngular 4 RequestOption 对象不可分配给 post 方法
【发布时间】:2018-06-02 07:42:18
【问题描述】:

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

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

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

但是如果我尝试在 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;
    });

我收到此错误消息

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'.

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

更新

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

let headers = new HttpHeaders();

并在 post 方法中使用此标头值

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

然后得到这个错误

[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...'.

我也试过了

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

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

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

【问题讨论】:

    标签: angular typescript ionic-framework


    【解决方案1】:

    @angular/http 已弃用

    改用@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))
        );
    }
    

    【讨论】:

      【解决方案2】:

      RequestOptions 类将与已弃用的 Http 模块一起使用,由于您收到此错误,我假设您使用的是 HttpClient 模块。

      如果您想设置 headersoptions ,如代码中所示,您可以使用类似这样的内容(Angular docs 中显示的简化版本):

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

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

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

      【讨论】:

      • 感谢您的回复,这里是我的构造函数:constructor(@Inject('apiUrl') private apiUrl, public http: HttpClient) { } 没看懂,我也在用HttpClient。我用你的提示试过了,但我想我又做错了。
      • 构造函数看起来不错。您能否更新问题中的 http 请求以显示它现在的样子?
      • 好的,我删除了requestOptions,让headers = new HttpHeaders();将其用于标题。我没有更改附加行然后试试这个:return this.http.post(url,JSON.stringify({username,password}), { options: { headers?: headers; } }) 我想这太错误了.. .
      • 应该很接近,在你的实际请求中不需要?(猫王运算符),它只是为了定义HttpHeaders类。您可以在最初的问题框中发布更新的代码,以便我可以一起查看吗?此外,当前出现的错误。
      • 好的,所以如果你使用选项,第一个版本会抛出错误 b/c,你必须重新格式化它以在选项中包含 bodyheader,见 @987654324 @。您的第二次尝试导致请求成功,因为此处抛出错误:.map(res=&gt;res.json())。最后一个错误是一个差异问题。
      【解决方案3】:
      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'));
        }
      

      【讨论】:

      • 感谢您的回复,如何将“授权”头设置为用户名+':'+'密码?
      • { '授权': ${username}:${password} }
      【解决方案4】:

      在服务中

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

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

      【讨论】:

        猜你喜欢
        • 2021-05-21
        • 1970-01-01
        • 2019-03-08
        • 1970-01-01
        • 2018-06-23
        • 1970-01-01
        • 1970-01-01
        • 2017-07-13
        • 2021-12-03
        相关资源
        最近更新 更多