html - Angular 4 - 从一个 api 获取 ID 并将其与另一个 api 的 url 连接
问题描述
我正在使用 Angular 4+。
我添加了一个获取公司列表的 API。针对该公司列表,我正在获取特定公司预订的服务。
为了获取特定公司预订的服务列表,我创建了一个函数getCompanyServices()
并在ngOnInit
我的 API 中调用它,如下所示:
www.example.com/company-service/255
其中 255 是另一个 api 获取的公司的 ID。
如果我只是{{company.id}}
在 html 视图中显示它会显示 id,但我如何在获取公司服务的 api url 中连接该 company.id?
我尝试过的方法:
- 在我的 component.ts 文件中创建一个变量 company_id,为其分配 data.company-id 但数据不解析。
- 在我调用 getCompanyServices() api 的函数中传递公司 ID,但我无法理解如何将数据解析到其中。
代码:demo.service.ts(用于访问 api)
getCompanies() {
return this.http.get('http://example.com/api/companies', httpOptions);
}
getCompanyServices() {
return this.http.get('http://example.com/v1/company-service', httpOptions);
}
services.component.ts 文件
companies: any=[];
services: any=[];
ngOnInit() {
this.getCompanies();
this.getCompanyServices();
}
getCompanies() {
this._demoService.getCompanies().subscribe(
(response:any) => { console.log("Response =" , response);
this.companies = response.data;
},
err => { console.error(err)},
() => { console.log("ALL Companies FETCHED!") }
)
}
getCompanyServices() {
this._demoService.getCompanyServices().subscribe(
(response:any) => { console.log("Response =" , response);
this.services = response.data;},
err => { console.error(err)},
() => { console.log("Services FETCHED!") }
)
}
HTML 文件
<p>{{company.id}}</p>
<p>{{company.name}}</p>
<button class="sidebar-services">Services</p>
解决方案
根据我从您的问题中了解到的情况,您需要获取 companyId 并为每个 companyId 获取其服务。您可以通过使用 flatMap 来实现它,如下所示:
this.subsc = this._demoService.getCompanies()
.pipe(flatMap((s) => {
this.companies.push(s);
return s.id;
}),
flatMap((id) =>{
return this._demoService.getCompanyServices(id).pipe(map((services) => {
return services;
}));
}))
.subscribe(res => {
this.services.push(res);
},
undefined,
() => console.log('complete'));
推荐阅读
- spring - 当通过表达式或自定义方法将实体列表映射到 dto 实体列表时,如何定位 Dto 的属性
- python - 在 Pandas 中检查字符串是否存在于另一列的值中的最有效方法
- sql - 提高子查询中限制的性能
- postgresql - 在 SQuirreL 中输出 PostgreSQL 的位类型会导致“
" - node.js - 穆尔特 | 不断收到““路径”参数必须是字符串类型。收到的类型号“
- apache-spark - 无法在后续会话中读取持久化的 Spark 仓库数据库
- java - 调试时是否可以立即将 log4j2 消息刷新到控制台?
- python - 另存为 py 导致 500:内部服务器错误
- linux - 删除基于一个文件的行包含到另一个
- add - CLIPS - 添加两个事实的插槽