Search code examples
angulartypescriptjson-deserialization

Get "Real Objects" (fields and methods) from Rest Request with Angular HttpClient


So I've had the same problem as this question.

The question was posted 2017, therefore I was wondering is there a better/easier way to do this now a days?

The most optimal thing that I had in mind would've been an HttpInterceptor so services and classes can look something like this:

@Injectable({
  providedIn: 'root'
})
export class ExampleService {
  constructor(private http: HttpClient) { }

  getHouse(): Observable<House> {
    return this.http.get<House>("MyRestPath");
  }
}

and then a class using it like this

someRandomMethod(): void {
    this.exampleService.getHouse().subscribe(house => {
      console.log(house.doSomething()) // Notice the method here
      console.log(house.address) // aswell as a field
    })
  }

Is that possible or do we still have to do it like in the question/answers mentioned above?


Solution

  • Interceptors could be used to archive it. While it would be like magic for any developer who would maintain this code. It be would quite a mix of concerns: the HTTP client would request the data from the backend and wrap it into another object. The single responsibility principle suggests us avoiding it. Service is for sure a better place to handle such logic.

    export class ExampleService {
      constructor(private http: HttpClient) { }
    
      getHouse(): Observable<House> {
        return this.http.get<HouseDto>("MyRestPath")
                   .pipe(map(house => new House(house)));
      }
    }