简体   繁体   中英

Values from web api are not being converted

I have a web api call. 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. 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

  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.

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
          }
       })
     )         
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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