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

时间:2021-07-10 19:40:09

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

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

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

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

{blocks: Array[]}

any inputs?

1 个解决方案

#1


1  

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.

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

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

#1


1  

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.

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

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