如何修改从MongoDB中恢复的JSON对象?

时间:2016-08-02 12:20:18

标签: json node.js mongodb angular

所以我正在进行休息调用以获取此JSON对象:

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

现在我想为这个对象添加一个数组,如下所示:

{  
    "_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
}

所以我尝试了以下:

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);
}

但它不修改当前对象,而是创建新的Object:

{blocks: Array[]}

任何输入?

1 个答案:

答案 0 :(得分:1)

那是因为你没有在c:\电话中分配它。由于JavaScript中HTTP请求的异步性质,subscribe调用下方的代码将在subscribe调用内的回调之前执行。

您可以通过移动回调中的代码轻松解决此问题:

subscribe