简体   繁体   中英

Why does the object first appear after calling the Api, but then it is undefined

I have a problem that I do not understand and I have not found an answer to it.

fetch(i.login.url, {
      method: i.login.methodType,
      body: JSON.stringify(data),
      headers: {
        "Content-Type": "application/json",
      },
    })
      .then((response) => {
        console.log(response);
        var prom;
        if (!response.ok) {
           prom = response.json() as Promise<ResultModel<boolean>>;
           prom.then((result) => {
           
           console.log("1: ",result);          // 1. Here is the object
           console.log("2: ",result.Message);  // 2. Here is undefined

          });
  1. Here is the object
{isSuccess: false, message: "Uživatel nepřihlášen. Email je null, nebo nevyplněný. (Parameter 'Email')", data: false}
> data: false
  isSuccess: false
  message: "Uživatel nepřihlášen. Email je null, nebo nevyplněný. (Parameter 'Email')"

This is the console output, and it is correct.

  1. Here is undefined
undefined

Here the value is undefined in the console and I don't understand why.

I tried this:

var p = new ResultModel<boolean>(result);
console.log(p);

ResultModel {IsSuccess: false, Message: '', Data: undefined}
>Data: undefined
 IsSuccess: false
 Message: ""
 [[Prototype]]: Object

but the result is again bad.

I don't understand what I'm doing wrong. Please advise, thank you.

your ResultModel has Captial M while the real object has " message key while you are logging with Message. key.

should be

console.log("2: ",result.message);

message uncapitalized

instead of

console.log("2: ",result.Message);

you can see that your keys are uncapitalized when you log the object, however your ResultModel show capitalized keys. So your ResultModel type is not correct

you can change the ResultModel in TypeScript the following way

type NewResultModel = {
  [Prop in keyof ResultModel as Uncapitalize<Prop & string>]: ResultModel[Prop]
}

Then replace your ResultModel with the NewResultModel

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