转换为函数时无法编译代码 [英] unable to compile a code when converted into a function

查看:21
本文介绍了转换为函数时无法编译代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下可以正常工作的代码.

I have the following piece of code which works correctly.

  public createData(data:Data):Observable<any>{
    console.log('contacting server at '+this.API_URL +this.NEW_DATA_URL +" with data "+data+ " with httpOptions "+httpOptions.withCredentials + ","+httpOptions.headers );

let newData = new Data(data)    
    let body = JSON.stringify(newQuestion); 
//I WANT TO MOVE THE CODE BELOW INTO A FUNCTION BUT AM GETTING COMPILATION ERROR
    this.loaderService.show();
    return this.http.post(this.NEW_QUESTION_URL,body,httpOptions)
      .pipe(tap(response => { 
        let httpEvent = <HttpEvent<any>>response;
        if(httpEvent.type === HttpEventType.Response)
        {
          console.log('response from backend service:', response);

          return result;
        }
        else {
          console.log("not an http response")
          return response;
        }
      })
      ,catchError(this.handleError)
        ,finalize(()=> this.loaderService.hide())); //error handler if Observable fails

  }

因为我可以重用部分代码,所以我想创建一个函数,但现在我遇到了编译错误.我无法找出错误所在.

As I can reuse some part of the code, I thought to create a function but now I am getting compilation errors. I am unable to find out what is the mistake.

新功能是

private sendMessage(url:string, body:any,httpOptions:any){
    this.loaderService.show();
    return this.http.post(url,body,httpOptions)
      .pipe(tap(response => { 

          let httpEvent = <HttpEvent<any>>response; //ERROR HERE - 'ArrayBuffer' cannot be converted to type 'HttpEvent<any>'.
          if(httpEvent.type === HttpEventType.Response)
          {
            console.log('response from backend service:', response);

            let result = <HttpResponse<any>>response;

            return result;
          }
          else {
            console.log("not an http response")
            return response;
          }
        })
        ,catchError(this.handleError)
        ,finalize(()=> this.loaderService.hide())); //error handler if Observable fails
    }

错误是src/app/web-to-backend-interface.service.ts(264,27) 中的错误:错误 TS2352: 类型ArrayBuffer"无法转换为类型HttpEvent"'.类型 'ArrayBuffer' 不能与类型 'HttpUserEvent' 进行比较.类型ArrayBuffer"中缺少属性type".

http.post 有几个重载方法,其中之一返回 Observable - angular.io/api/common/http/HttpClient#post.如何让 Angular 使用返回 Observable 的重载版本?我更改了代码并添加了 responseType:'json' 但这也不起作用

http.post has several overloaded methods and one of them return Observable - angular.io/api/common/http/HttpClient#post. How do I make Angular use the overloaded version which returns Observable<T>? I changed the code and added responseType:'json' but that didnt work either

const httpOptions = {
  headers: new HttpHeaders({ 'Content-Type': 'application/json' }),
  withCredentials: true, 
observe: 'response' as 'response', 
  responseType: 'json' 
};


let observable:Observable<HttpEvent<any>> = this.http.post(url,body,httpOptions)
    return observable.pipe(tap((httpEvent:HttpEvent<any>) => {....}

我看到的错误是

ERROR in src/app/web-to-backend-interface.service.ts(80,71): error TS2345: Argument of type '{ headers: HttpHeaders; withCredentials: boolean; observe: "response"; responseType: string; }' is not assignable to parameter of type '{ headers?: HttpHeaders | { [header: string]: string | string[]; }; observe?: "body"; params?: Ht...'.
  Types of property 'observe' are incompatible.
    Type '"response"' is not assignable to type '"body"'.
src/app/web-to-backend-interface.service.ts(111,52): error TS2345: Argument of type '{ headers: HttpHeaders; withCredentials: boolean; observe: "response"; responseType: string; }' is not assignable to parameter of type '{ headers?: HttpHeaders | { [header: string]: string | string[]; }; observe?: "body"; params?: Ht...'.
  Types of property 'observe' are incompatible.
    Type '"response"' is not assignable to type '"body"'.
src/app/web-to-backend-interface.service.ts(195,73): error TS2345: Argument of type '{ headers: HttpHeaders; withCredentials: boolean; observe: "response"; responseType: string; }' is not assignable to parameter of type '{ headers?: HttpHeaders | { [header: string]: string | string[]; }; observe?: "body"; params?: Ht...'.
src/app/web-to-backend-interface.service.ts(215,72): error TS2345: Argument of type '{ headers: HttpHeaders; withCredentials: boolean; observe: "response"; responseType: string; }' is not assignable to parameter of type '{ headers?: HttpHeaders | { [header: string]: string | string[]; }; observe?: "body"; params?: Ht...'.
src/app/web-to-backend-interface.service.ts(250,54): error TS2345: Argument of type '{ headers: HttpHeaders; withCredentials: boolean; observe: "response"; responseType: string; }' is not assignable to parameter of type '{ headers?: HttpHeaders | { [header: string]: string | string[]; }; observe?: "body"; params?: Ht...'.
src/app/web-to-backend-interface.service.ts(290,9): error TS2322: Type 'Observable<ArrayBuffer>' is not assignable to type 'Observable<HttpEvent<any>>'.
  Type 'ArrayBuffer' is not assignable to type 'HttpEvent<any>'.
    Type 'ArrayBuffer' is not assignable to type 'HttpUserEvent<any>'.
      Property 'type' is missing in type 'ArrayBuffer'.
src/app/web-to-backend-interface.service.ts(296,59): error TS2552: Cannot find name 'response'. Did you mean 'Response'?

为什么将工作代码单独制作一个函数会使其不可编译?我的错误是什么?

Why does making a separate function of a working code makes it non-compilable? What is my mistake?

推荐答案

我能够解决它,但现在我留下的问题多于答案.如果有人能向我解释这种行为,我们将不胜感激.

i was able to solve it but now I am left with more questions than answers. Would appreciate if someone could explain the behaviour to me.

我使用了以下 httpOptions 对象

const httpOptions = {
  headers: new HttpHeaders({ 'Content-Type': 'application/json' }),

withCredentials: true, 
observe: 'response' as 'response', 

};

在代码中的某些地方如下使用它.

as was using it as follows in some places in the code.

 return this.http.post(this.SIGNUP_USER_URL,body,httpOptions)

这奏效了.

然后我想到将 http.post 更改为函数 sendMessage(如问题中所述)并仅替换一次(请记住我使用的是 sendMessagecode>this.http.post 在几个地方,所以想从一个地方开始尝试).我注意到使用 httpOptions 使 post 返回 Observable.

Then I thought of changing the http.post into a function sendMessage (as explained in the question) and replaced it in only once place (remember I am using this.http.post in several places so wanted to try it at one place to begin with). I noticed that using httpOptions made post return Observable<ArrayBuffer>.

疑问 1 - 为什么?

Doubt 1 - why?

然后我将 httpOptions 改为

const httpOptions = {
  headers: new HttpHeaders({ 'Content-Type': 'application/json' }),

withCredentials: true, 
observe: 'response' as 'response', 
responseType:'json'  
};

它开始在我直接使用 http.post 的地方给我错误(没有 sendMessage.错误是

It started giving me errors at places where I am using http.post directly (without sendMessage. The error was

ERROR in src/app/web-to-backend-interface.service.ts(81,71): error TS2345: Argument of type '{ headers: HttpHeaders; withCredentials: boolean; observe: "response"; responseType: string; }' is not assignable to parameter of type '{ headers?: HttpHeaders | { [header: string]: string | string[]; }; observe?: "body"; params?: Ht...'.
  Types of property 'observe' are incompatible.
    Type '"response"' is not assignable to type '"body"'.
src/app/web-to-backend-interface.service.ts(112,52): error TS2345: Argument of type '{ headers: HttpHeaders; withCredentials: boolean; observe: "response"; responseType: string; }' is not assignable to parameter of type '{ headers?: HttpHeaders | { [header: string]: string | string[]; }; observe?: "body"; params?: Ht...'.
  Types of property 'observe' are incompatible.
    Type '"response"' is not assignable to type '"body"'.
src/app/web-to-backend-interface.service.ts(196,73): error TS2345: Argument of type '{ headers: HttpHeaders; withCredentials: boolean; observe: "response"; responseType: string; }' is not assignable to parameter of type '{ headers?: HttpHeaders | { [header: string]: string | string[]; }; observe?: "body"; params?: Ht...'.
src/app/web-to-backend-interface.service.ts(216,72): error TS2345: Argument of type '{ headers: HttpHeaders; withCredentials: boolean; observe: "response"; responseType: string; }' is not assignable to parameter of type '{ headers?: HttpHeaders | { [header: string]: string | string[]; }; observe?: "body"; params?: Ht...'.
src/app/web-to-backend-interface.service.ts(251,54): error TS2345: Argument of type '{ headers: HttpHeaders; withCredentials: boolean; observe: "response"; responseType: string; }' is not assignable to parameter of type '{ headers?: HttpHeaders | { [header: string]: string | string[]; }; observe?: "body"; params?: Ht...'.
src/app/web-to-backend-interface.service.ts(291,9): error TS2322: Type 'Observable<ArrayBuffer>' is not assignable to type 'Observable<HttpEvent<any>>'.
  Type 'ArrayBuffer' is not assignable to type 'HttpEvent<any>'.
    Type 'ArrayBuffer' is not assignable to type 'HttpUserEvent<any>'.
      Property 'type' is missing in type 'ArrayBuffer'.

所以我从 httpOptions 中删除了 responseType:'json' 并在我的 this.http.post 中添加了一个显式对象sendMessage 成功了!

So I removed responseType:'json' from httpOptions and added an explicit object in this.http.post in my sendMessage which worked!

private sendMessage(url:string, body:any,httpOptions){
  ...
    let observable:Observable<HttpEvent<any>> = this.http.post(url,body,{
          headers: new HttpHeaders({ 'Content-Type': 'application/json' }),
          withCredentials: true,
          observe: 'events',
          responseType: 'json'
        })
...
}

observe 和 responseType 之间似乎有关系.例如,observe=body 和 responseType=text 意味着 post 应该观察(查看)正文,将其解释为文本并返回 Observable.但我想知道为什么我不能改变 httpOptions

there seem to be relationship between observe and responseType. Eg observe=body and responseType=text means that post should observe (look in) the body, interpret it as text and return Observable. But I wonder why I just couldn't change httpOptions

这篇关于转换为函数时无法编译代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆