Angular: Iterate over nested object using resolver

79 views Asked by At

I have this resolver service for my admin module:

constructor(private userservice: UserService) { }

  resolve(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): Observable<any> {
    return this.userservice.getUserById(route.paramMap.get('id'));
  }
}

The fethed data in a detail component

export class AdminDetailComponent implements OnInit {
  user: any;
  constructor(private route: ActivatedRoute) {}
  ngOnInit() {
    this.route.data.subscribe((data:any) => {
      this.user=Array.of(data);
      console.log(this.user)
    });
  }
}

The routes of admin

const routes: Routes = [

  {path:'', component:AdminComponent},
  {
    path:'user/:id',
    component:AdminDetailComponent,
    resolve: {
      adminUser: UserResolverService
    }
  }
];

The HTML

<div class="container">
  <div class="row">
    <div class="col-md-12" *ngFor="let u of user">
      {{u.username}}
    </div>
  </div>
</div>

this is the structure of the fetched data

[{…}]
0:
adminUser: {username: "spacecadet", password: "12345", id: 2}
__proto__: Object
length: 1
__proto__: Array(0)

I've tried all I can remember but I cant get a loop for rendering the data. Can someone sort me out?

1

There are 1 answers

4
bryan60 On BEST ANSWER

in your init, you just need this...

this.user = data;

and in your ngFor, you need to access the properties correctly....

{{u.adminUser.username}}