【发布时间】:2021-10-21 12:27:37
【问题描述】:
我正在学习 Angular 和 API 服务。目前,我使用router 重定向到使用group id 的组详细信息页面
这是我想要实现的目标:
在详细页面中,我想在角度页面中显示用户名和用户城市,这需要多次API调用(可能需要按顺序)才能从中获取数据group data。
- 我需要使用
route id/group id通过getGroup()获取组对象 - 每个组包含多个用户 ID
- (获取用户名)我需要迭代每个 用户 ID 以获取包含 用户名 和 城市 ID 的
user objectgetUser() - (获取城市名称)我需要遍历每个 city Ids 以获取包含 city ids 和 city names 的
city objectgetCity()
所有数据概览:
######### group data
{
"groups": [
{
"id": "group_id1",
"users": ["user_id1", "user_id2"]
},
{
"id": "group_id2",
"users": ["user_id3", "user_id4"]
}
]
}
######### user data
{
"users": [
{
"id": "user_id1",
"city": ["city_id1", "city_id2"]
},
{
"id": "user_id2",
"city": ["city_id3", "city_id4"]
},
{
"id": "user_id3",
"city": ["city_id1", "city_id3"]
},
{
"id": "user_id4",
"city": ["city_id2", "city_id4"]
}
]
}
######### city data
{
"cities": [
{
"id": "city_id1",
"name": "NY"
}
{
"id": "city_id2",
"name": "BOS"
}
{
"id": "city_id3",
"name": "SF"
}
{
"id": "city_id4",
"name": "LA"
}
]
}
目前,我可以获取 group ,但我不知道如何获取用户名和城市。
## component.ts
export class displayComponent implements OnInit {
group$!: Observable<group>;
constructor(
private router: Router,
private route: ActivatedRoute,
private groupService: GroupService,
private userService: UserService,
private cityService: CityService,
) {}
ngOnInit(): void {
this.group$ = this.route.params.pipe(
switchMap((params) => this.groupService.getGroup(params.id))
);
// how to iterate all **user Id** to get user names via `getUser(**user Id**)`
// how to iterate all **city Id** to get city names via `getCity(**city Id**)`
}
## html
<div *ngIf="group$ | async as group">
<p> {{ group.id }} </p>
<!-- user names placeholder-->
<!-- user city names placeholder-->
</div>
【问题讨论】:
标签: angular typescript async-await rxjs pipe