2016-08-02 73 views
0

所以我想提出一個REST調用來得到這個JSON對象:如何修改MongoDB中的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); 
} 

但它不是修改當前的對象,而不是它的創建新的對象爲:

{blocks: Array[]} 

是否有輸入?

回答

1

這是因爲您沒有在subscribe調用中分配它。由於JavaScript中HTTP請求的異步性質,subscribe調用下的代碼將在subscribe調用中的回調之前執行。

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

您可以輕鬆地將代碼移動到回調內部解決這個問題