Angular 6 HttpClient return instance of class

前端 未结 1 743
Happy的楠姐
Happy的楠姐 2021-01-12 08:45

Before angular\'s new HttpClient was introduced, our objects returned from the http api call could be validated with the instanceof keyword. they no longer can

1条回答
  •  一整个雨季
    2021-01-12 09:11

    TypeScript uses structural typing, i.e. c object doesn't have to be an instance of Cow class to conform to Cow type.

    TypeScript types exist only at compilation time and don't affect JS output in any way (with the exception of emitted types which are used for Angular DI). as Cow asserts that res conforms to Cow type, while instanceof Cow expects that c is an instance of Cow class. Since Cow wasn't instantiated, cow instanceof Cow is false.

    A class should be designed to support hydration (possibly via constructor parameters) and be instantiated explicitly:

    class Cow {
      sound: string;
    }
    
    return this.http.get(ApiRoute.GET_COW, options)
        .map(res => Object.assign(new Cow(), res as Cow))
        .toPromise()
        .then((c: Cow) => {
            console.log(c instanceof Cow);
        })
    

    If some logic is needed to construct Cow instance from plain object (validation, nested object construction), this can be done in class constructor or separate helper function (e.g. Cow static method).

    0 讨论(0)
提交回复
热议问题