在angular2中使用HttpParams的Http返回404错误

时间:2019-11-27 09:07:21

标签: angular angular-httpclient

这可能很简单,我只是想念一些东西。我有一个GET端点,正在尝试从Angular UI调用它。我想将时间戳发送给端点作为参数。我做了基本的方法:

 
    return this.http.get(this.Uri + academyId + "?dateWhenToCalculate=" + (dateWhenToCompute.getTime() / 1000).toString()).pipe(   
        map((res: Response) => res.json() as Model),
        catchError(this.handleError));

使用该网址,我得到以下网址:http://host/api/route/1?dateWhenToCalculate=1572991200。我的端点就像:

    [HttpGet]
    [GenericAuthorizeFilter]
    [Route("route/{academyId}")]
    public IHttpActionResult ComputePlayerScores(int academyId, string dateWhenToCalculate){....}

使用这种创建url的方式一切正常。但是,当我尝试使用HttpParams进行操作时,我总是收到一个奇怪的URL,当然还有404错误。

    let httpParams = new HttpParams()
        .set('dateWhenToCalculate', (dateWhenToCompute.getTime() / 1000).toString());

    return this.http.get(this.Uri+ academyId, { params: httpParams}).pipe(
        map((res: Response) => res.json() as Model),
        catchError(this.handleError));

使用HttpParams我得到了

  

URL:http://host/api/route/1?updates=%7B%22param%22:%22dateWhenToCalculate%22,%22value%22:%221573423200%22,%22op%22:%22s%22%7D&cloneFrom=%7B%22updates%22:null,%22cloneFrom%22:null,%22encoder%22:%7B%7D,%22map%22:null%7D&encoder=%7B%7D&map=null

我错过了什么吗?

2 个答案:

答案 0 :(得分:1)

 

这是 HttpParams 需要使用的最少代码量。在这里,我使用的是测试API,但是用您的网址更改了该部分

AppModule文件的app.module.ts

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

@NgModule({
  imports: [ HttpClientModule ],
  ......
})
export class AppModule { }

首先需要在组件或服务上进行以下导入:

import { HttpClient } from '@angular/common/http';
import { HttpParams } from "@angular/common/http";

然后像下面的代码一样使用HttpParams

const options =  { params: new HttpParams().set('postId', '1') };
this.http.get('https://jsonplaceholder.typicode.com/comments' , options)
    .subscribe((data)=> {console.log(data)});

您也可以尝试以下方法,而不是new HttpParams().set('postId', '1')

const options =  { params: new HttpParams({fromString: 'postId=1'}) };

工作示例为here


以下部分未经我测试。我从这个link找到了它。这是一种查询参数未按预期编码的解决方案。

  1. 创建一个实现HttpParameterCodec的类。或者, 您还可以扩展HttpUrlEncodingCodec
  2. encodeKeyencodeValue函数需要对值进行编码。 香草JavaScript允许您使用encodeURIComponent
  3. 在创建新的HttpParams: new HttpParams({ encoder: new CustomHttpParamEncoder() })时使用自定义编码器类。重要的 部分是encodeURIComponent的用法,这是一种香草 使用JavaScript函数对字符串进行编码。

自定义解码器可能类似于:

import { HttpParameterCodec } from '@angular/common/http';
export class CustomHttpParamEncoder implements HttpParameterCodec {
  encodeKey(key: string): string {
    return encodeURIComponent(key);
  }
  encodeValue(value: string): string {
    return encodeURIComponent(value);
  }
  decodeKey(key: string): string {
    return decodeURIComponent(key);
  }
  decodeValue(value: string): string {
    return decodeURIComponent(value);
  }
}

希望这对您有帮助!

答案 1 :(得分:0)

您的端点是route/{academyId},但是您正在呼叫http:/host/api/route/endpoint/1,该端点在endpoint和您的ID之间具有route令牌。请在您的http请求中删除此endpoint令牌。

/ uri之后,您只有http。请加倍。