Nhat Dang Nhat Dang - 1 year ago 121
AngularJS Question

Angular 2 - http get return wrong object

I'm using @angular/http get to fetch data from server, here is my code :

private _currentPT: any;
public phongtroDetailChange = new Subject();

layPhongtro(id: number): Promise<any> {
return new Promise((resolve, reject) => {
.get(Constants.apiUrl + 'phongtro/' + id, { headers: Constants.headers })
.map((resp: Response) => resp.json())
.subscribe(resp => {
// if (!resp.result) {
// this._currentPT = resp;
// this.phongtroDetailChange.next(true);
// resolve(resp);
// } else {
// this.handleError('layPhongtro', resp.result);
// reject(resp.result);
// }
error => this.handleError('layPhongtro', error));

When I commented code like that, the property "tiencoc" of resp has right value which means its value is 0, here is the picture of console.log


But when I uncommented, the value of "tiencoc" is the same as property "giatien", now its value is 1000000, here is picture of console.log when uncommented


I dont know why ? Pls help me, thank you so much

P/s: I have tested with POSTMAN and the resp is OK, which means "tiencoc"'s value is 0

Answer Source

Here's a fiddle for demo: https://jsfiddle.net/Lg6L8n2m/ (guess what the value is before you look at the log :))

As I've mentioned it the comment when you JSON.stringify the response object you are printing that value (because strings are immutable in js). But without stringify, console.log works actually somewhat "asynchronously", console.log prints the latest value that the object has.

So you are changing the tientoc to be 1000000 somewhere in your code after your console.log. And console.log prints you the latest value. From what I see it might be in the block where you subscribe to your Subject phongtroDetailChange

I suggest reading Immutability in javascript about this problem.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download