簡體   English   中英

在Promise中返回自定義類型

[英]Return custom type in Promise

我有一些如下所示的JSON數組,並且從服務中獲取了這些JSON。

[{
    "id": 3,
    "name": "Arun"
}, {
    "id": 5,
    "name": "Barun"
}, {
    "id": 1,
    "name": "Joy"
}, {
    "id": 8,
    "name": "Suman"
}]

現在,我在下面做了一個

class Person{
  id:number
  name:string

    deserialize(input) {
      this.id = input.id;
      this.name = input.name
      return this;
   }
}

現在,我有了一個服務類,從那里可以通過Promise獲取JSON(Array / dictionary),並將該Promise發送到解析函數。 我的解析功能如下

 private  parse(response:Promise<{}>):Promise<{}>{

    return new Promise((success,failure) =>{
        response.then((result) => {
            if (result instanceof Array || Array.isArray(result)){
                let rs1 = result.map((val) => new Person().deserialize(val)) 
                success(rs1);
            }else{
                success(new Person().deserialize(result))
            }
        },(err) => {
            failure(err)
        });
    });
}

現在,我有兩個功能

  expectingObjectOfPerson(){
    //get the promise from service class
    let result = servicePromise//Promise from service class with JSON

    //now call parse function 
    this.parse(result)
    .then((response) => {

        //I knew that response is an object of Person in run time.
        let person = response as Person

        //log name of this person
        console.log(person.name) //no run time exception

        //log name of this person
        console.log(person.nam) //Error thrown by compiler

        //now if I do this 
        console.log(response.name) //no run time exception

        //if this 
        console.log(response.nam) //run time exception, also no error thrown from compiler


        /* Main problem is on here.
        * Is there any way that response could automatically inferred to Person */
    }, (error) => {
        Console.log(error);
    })

}

expectingArrayOfPerson(){
     //get the promise from service class
     let result = servicePromise//Promise from service class with JSON

     //now call parse function 
     this.parse(result)
     .then((response) => {

         //I knew that response is an object of Person in run time.
         let persons = response as Person[]

         //log name of this person
         console.log(persons.map((val) => val.name)) //no run time exception

         //log name of this person
         console.log(persons.map((val) => val.name)) //Error thrown by compiler

         //now if I do this 
         console.log(response.map((val) => val.name)) //no run time exception

         //if this 
         console.log(persons.map((val) => val.name)) //run time exception , also no error thrown from compiler


         /* Main problem is on here.
         * Is there any way that response could automatically inferred to array of Person */
     }, (error) => {
         Console.log(error);
     })
}

有什么方法可以將響應自動推斷為Person對象或Person數組取決於響應? 我是Angular的新手,任何幫助將不勝感激。

我正在使用最新版本的Typescript。

首先,讓我們來看一下您的服務:您正在創建一個Promise,以履行另一個承諾。 在重復自己。

此外,您應該使用Observables,它們是已升級的Promise。

最后,您每次都會創建一個新的Person對象。 考慮使用靜態方法反序列化。

這給您:

export function parse(response: Promise<{}>): Observable<{}> {
  // Rx 6 : return fromPromise(response)
  return Observable.fromPromise(response)
    .map(result => {
      if (result instanceof Array || Array.isArray(result)) {
        return result.map((val) => Person.deserialize(val))
      } else {
        return Person.deserialize(result);
      }
    })
}

export class Person {
  id: number;
  name: string;

  public static deserialize(input: any): Person {
    const person = new Person();
    person.id = input.id;
    person.name = input.name;
    return person;
  }
}

現在,您可以像這樣使用兩個函數:

expectingObjectOfPerson(){
  this.parse(servicePromise) // Whatever it is
    .subscribe(personInstance => {
      console.log(personInstance);
      console.log(personInstance instanceof Person);
    }, error => console.log(error));
}

expectingArrayOfPerson(){
  this.parse(servicePromise) // Whatever it is
  .subscribe(persons => {
    for (const personInstance of persons) {
      console.log(personInstance);
      console.log(personInstance instanceof Person);
    }
  }, error => console.log(error));
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM