首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >转换为函数时无法编译代码

转换为函数时无法编译代码
EN

Stack Overflow用户
提问于 2018-08-15 14:49:44
回答 2查看 883关注 0票数 0

我有下面这段代码,它可以正确地工作。

代码语言:javascript
运行
复制
  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

  }

因为我可以重用代码的一部分,所以我想创建一个函数,但现在我得到了编译错误。我找不出错误是什么。

新函数是

代码语言:javascript
运行
复制
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 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',但这也不起作用

代码语言:javascript
运行
复制
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>) => {....}

我看到的错误是

代码语言:javascript
运行
复制
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'?

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

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-08-16 13:45:54

我能够解决它,但现在我留下的问题比答案更多。如果有人能给我解释一下他的行为我会很感激的。

我使用的是以下httpOptions对象

代码语言:javascript
运行
复制
const httpOptions = {
  headers: new HttpHeaders({ 'Content-Type': 'application/json' }),

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

};

就像在代码中的某些地方使用它一样。

代码语言:javascript
运行
复制
 return this.http.post(this.SIGNUP_USER_URL,body,httpOptions)

这起作用了。

然后,我考虑将http.post改为函数sendMessage (如问题中所述),并只在一个地方替换它(请记住,我在多个地方使用this.http.post,所以我想从一个地方开始尝试它)。我注意到使用httpOptions会让post返回Observable<ArrayBuffer>

疑问1-为什么?

然后,我将httpOptions更改为

代码语言:javascript
运行
复制
const httpOptions = {
  headers: new HttpHeaders({ 'Content-Type': 'application/json' }),

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

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

代码语言:javascript
运行
复制
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',并在我的sendMessage中的this.http.post中添加了一个显式对象,它起作用了!

代码语言:javascript
运行
复制
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'
        })
...
}

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

票数 0
EN

Stack Overflow用户

发布于 2018-08-16 13:18:33

虽然我不能回答为什么你现在会得到一个TS错误,而你以前没有,但我可以建议你如何摆脱它(假设代码在你重构之前是有效的)。如果你在声明中给response一个类型,那么它就不会得到你必须尝试和映射的假设类型:

代码语言:javascript
运行
复制
.pipe(tap((response: HttpEvent<any>) => { 

      let httpEvent = response; // No need for type-casting here anymore.
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51854143

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档