Angular:使用解析器迭代嵌套对象
Angular: Iterate over nested object using resolver
我的管理模块有这个解析器服务:
constructor(private userservice: UserService) { }
resolve(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot
): Observable<any> {
return this.userservice.getUserById(route.paramMap.get('id'));
}
}
详情组件中的数据
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)
});
}
}
管理员的路由
const routes: Routes = [
{path:'', component:AdminComponent},
{
path:'user/:id',
component:AdminDetailComponent,
resolve: {
adminUser: UserResolverService
}
}
];
HTML
<div class="container">
<div class="row">
<div class="col-md-12" *ngFor="let u of user">
{{u.username}}
</div>
</div>
</div>
这是抓取数据的结构
[{…}]
0:
adminUser: {username: "spacecadet", password: "12345", id: 2}
__proto__: Object
length: 1
__proto__: Array(0)
我已经尝试了所有我记得的方法,但我无法获得用于呈现数据的循环。有人可以帮我解决一下吗?
在你的初始化中,你只需要这个...
this.user = data;
并且在您的 ngFor 中,您需要正确访问属性....
{{u.adminUser.username}}
我的管理模块有这个解析器服务:
constructor(private userservice: UserService) { }
resolve(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot
): Observable<any> {
return this.userservice.getUserById(route.paramMap.get('id'));
}
}
详情组件中的数据
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)
});
}
}
管理员的路由
const routes: Routes = [
{path:'', component:AdminComponent},
{
path:'user/:id',
component:AdminDetailComponent,
resolve: {
adminUser: UserResolverService
}
}
];
HTML
<div class="container">
<div class="row">
<div class="col-md-12" *ngFor="let u of user">
{{u.username}}
</div>
</div>
</div>
这是抓取数据的结构
[{…}]
0:
adminUser: {username: "spacecadet", password: "12345", id: 2}
__proto__: Object
length: 1
__proto__: Array(0)
我已经尝试了所有我记得的方法,但我无法获得用于呈现数据的循环。有人可以帮我解决一下吗?
在你的初始化中,你只需要这个...
this.user = data;
并且在您的 ngFor 中,您需要正确访问属性....
{{u.adminUser.username}}