简体   繁体   中英

Angular - Parse nested JSON

I have an Angular 12 application and am getting back a complex type, which I have mapped to interfaces.

When I console.log this object, I see the values I am expecting, however trying to log the members array here comes back as undefined.

成员存在

My Angular code is:

this.conferenceService
  .getConferenceBridge(this.selectedConferenceBridgeBoxnum)
  .subscribe((cb) => {
    this.conferenceBridge = cb;
    console.log(cb.members); <--- says it's undefined
}

The interface has "members" as an array.

members: ConferenceBridgeMember[];

Why is this undefined here? This isn't a parsing problem as I can see this array after the .get and it looks fine.

I thing the problem in the mapping into getConferenceBridge function so try to remove it first if it is fixed so the mapping the mainly issue

and you can try this approach to cast the object as in the example below with Typescript

//some interfaces
    interface Item{
        id:number,
        name:string
    }
    
    interface Box{
        id:101,
        items:Item[]
    }
// fake object similar to the interfaces
    const box = {
        items:Array([
            {
                id:1,
                name:'item 1'
            },
            {
                id:2,
                name:'item 1'
            }
        ])
    }

// casting function
    function cast<T>(obj:any):T{    
        return obj as T;
    }

// here i will found the item had printed successfully 
    console.log(  cast<Box>(box).items[0] );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM