简体   繁体   English

来自 web api 的值没有被转换

[英]Values from web api are not being converted

I have a web api call.我有一个 web api 调用。 The property of checkNumber is a double on the web api side , however in my typescript model I need it to come in as a string. checkNumber 的属性在 web api 端是一个双精度值,但是在我的打字稿模型中,我需要它作为字符串输入。 It is staying as a number even though my model clearly has it as a string variable.即使我的模型清楚地将它作为字符串变量,它仍然是一个数字。

Is there a way to get the conversion to automatically happen to string?有没有办法让转换自动发生在字符串上?

my web api call我的 web api 调用

  public GetMyClass(myModel: MyClass): Observable<MyClass> {
        let headers = new HttpHeaders();
        headers.append("content-type", "application/json");
        headers.append("accept", "application/json");
        let options = { headers: headers };       
        return this.httpClient.post<MyClass>( url, myModel, options)         
      }

my model我的模特

export MyClass{
checkNumber?: string;
}

Typescript doesn't do auto conversion.打字稿不做自动转换。 It helps with type checking during development.它有助于在开发过程中进行类型检查。 At runtime, it just plain javascript.在运行时,它只是普通的 javascript。

You will need to define your own conversion.您需要定义自己的转换。

public GetMyClass(myModel: MyClass): Observable<MyClass> {
    let headers = new HttpHeaders();
    headers.append("content-type", "application/json");
    headers.append("accept", "application/json");
    let options = { headers: headers };       
    return this.httpClient.post<MyClass>( url, myModel, options)
     .pipe(
       map(dataObject => {
        let checkNumber = dataObject.checkNumber
        return { 
           checkNumber: checkNumber ? dataObject.checkNumber.toString() : undefined, 
           ...dataObject
          }
       })
     )         
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM