简体   繁体   中英

displaying an object in Angular 5

I ahve created a variable that gets its data from Firebase. It returns an object with the two parts to the object within it, however when I try to use string interpolation it returns [object Object] . I have tried doing an *ngFor however I get this error:

Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays

This is my variable:

this.groupMembers = this.currentGroup.members_uid;
    console.log(this.groupMembers)

the console.log returns this in the console:

  {7TkrG4Ty2pf2OBy9whhSsSl1sC22: true, by285gAhkdRg4rDMkujzSQXxGAJ2: true}
7TkrG4Ty2pf2OBy9whhSsSl1sC22
:
true
by285gAhkdRg4rDMkujzSQXxGAJ2
:
true
__proto__
:
Object
  1. How do I access this to display its content in my html?

  2. How do I create a new variable in my ts file that also 'loops' through them in some way so I can access each part individually?

EDIT ****

 this.currentGroup = this.currentGroupId$
        .pipe(switchMap(id => this._group.getGroupById(id).valueChanges()))

this then returns an Observable which I input to a child component like so:

*ngIf="currentGroup | async as group" [currentGroup]="group"

and call it:

@Input() currentGroup: any;

I believe AngularJs used to display the contents of an object when interpolated. This isn't a behavior supported by default in Angular, but it is easy to implement.

The quick and dirty way would be to add a function to your component that converts an object to a string using JSON.stringify() . A cleaner solution would be to create a Pipe to perform that same activity:

@Pipe({
  name: 'stringify'
})
export class StringifyPipe implements PipeTransform {
  transform(value: any, args?: any): any {
    return JSON.stringify(value);
  }
}

One you add the Pipe you can display it in your code template quite simply.

<pre>{{groupMembers | stringify}}</pre>

You can easily extend the Pipe to format the code so the display is nicer, or you can create a component that renders it nicely as html instead of using a pre element. Heck, I'm surprised a component doesn't already exist.

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