I created a Foobar class with a custom toString() method that works perfectly fine in most cases, except when the Foobar object is returned from a REST call. The following code snippet and its output demonstrate this issue: FOOBAR-1 behaves as expected, while FOOBAR-2 does not return a string but an Object instead. Why is this happening? On the other hand, FOOBAR-3 returns the expected result, indicating that it recognizes it as a Foobar object.
app.component.ts
import { HttpClient } from '@angular/common/http';
import { Component, ViewChild } from '@angular/core';
import { Foobar } from './foobar';
import { Observable } from 'rxjs';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
constructor(private http: HttpClient) {
}
ngAfterViewInit() {
console.log("FOOBAR-1 IS " + new Foobar().toString());
const remoteUrl:string = 'http://localhost:8080/foobar';
let observable:Observable<Foobar> = this.http.get<Foobar>(encodeURI(remoteUrl));
observable.subscribe(
(foobar: Foobar) => {
console.log("FOOBAR-2 IS "+foobar.toString());
console.log("FOOBAR-3 IS "+foobar.foo);
}
);
}
}
foobar.ts
export class Foobar {
foo:string ='bar';
toString(): string {
return this.foo;
};
}
Console output:
app.component.ts:18 FOOBAR-1 IS bar
app.component.ts:23 FOOBAR-2 IS [object Object]
app.component.ts:24 FOOBAR-3 IS bar
Why does the toString() method behave unexpectedly on objects returned from HttpClient requests? What exactly is causing this behavior?