Bhushan Gadekar Bhushan Gadekar - 4 months ago 10
JSON Question

How to modify JSON Object retrived from MongoDB?

So I am making a rest call to get this JSON Object:

{
"_id":"57a0811276e75ba815d248b0",
"gName":"demo-layout",
"gType":"Content",
"wsId":"57a036c376e75ba815d248ac",
"desc":"Demo-Layout for rapidpage",
"createdDate":"2016-08-02T11:16:34.223Z",
"__v":0
}


Now I want to add an array to this object ,something like this:

{
"_id":"57a0811276e75ba815d248b0",
"gName":"demo-layout",
"gType":"Content",
"wsId":"57a036c376e75ba815d248ac",
"desc":"Demo-Layout for rapidpage",
"createdDate":"2016-08-02T11:16:34.223Z",
"blocks":[], //should be added at runtime
"__v":0
}


So I tried following:

dbPage:any={};
ngOnInit(){
let pageId:string="57a0811276e75ba815d248b0";
this._pagesService.getPageById(pageId).subscribe((Page)=>{
this.dbPage=rapidPage;
console.log(this.dbPage); //this prints the object as shown above
});
this.dbPage.blocks=[];
this.dbPage.blocks.push(block1);
}


But its not modifying the current object,instead its creating new Object as :

{blocks: Array[]}


any inputs?

Answer

That's because you're not assigning it in the subscribe call. Due to the async nature of HTTP requests in JavaScript, the code below the subscribe call will be executed before the callback inside the subscribe call.

You can easily fix this by moving the code inside the callback:

dbPage: any = {};
ngOnInit(){
    let pageId: string = "57a0811276e75ba815d248b0";
    this._pagesService.getPageById(pageId).subscribe((rapidPage) => {
        this.dbPage = rapidPage;
        console.log(this.dbPage); //this prints the object as shown above   

        this.dbPage.blocks = [];
        this.dbPage.blocks.push(block1);
    });
}