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

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

问题描述

我有以下一段正确的代码.

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
    }

ERROR是 ERROR in src/app/web-to-backend-interface.service.ts(264,27): error TS2352: Type 'ArrayBuffer' cannot be converted to type 'HttpEvent<any>'. Type 'ArrayBuffer' is not comparable to type 'HttpUserEvent<any>'. Property 'type' is missing in type 'ArrayBuffer'.

ERROR is ERROR in src/app/web-to-backend-interface.service.ts(264,27): error TS2352: Type 'ArrayBuffer' cannot be converted to type 'HttpEvent<any>'. Type 'ArrayBuffer' is not comparable to type 'HttpUserEvent<any>'. Property 'type' is missing in type 'ArrayBuffer'.

http.post有几个重载方法,其中一个返回Observable-angular.io/api/common/http/HttpClient#post.如何使Angular使用返回Observable<T>的重载版本?我更改了代码并添加了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(如问题中所述),并仅在一次替换(请记住我在多个地方使用this.http.post,所以想一次尝试开始的地方).我注意到使用httpOptions使post返回Observable<ArrayBuffer>.

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-为什么?

然后我将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',并在我的sendMessagethis.http.post中添加了一个明确的对象!

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表示帖子应观察(查看)正文,将其解释为文本并返回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天全站免登陆