首页 > 解决方案 > 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?

我尝试过的方法:

  1. 在我的 component.ts 文件中创建一个变量 company_id,为其分配 data.company-id 但数据不解析。
  2. 在我调用 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>

标签: htmlangularapifetch

解决方案


根据我从您的问题中了解到的情况,您需要获取 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'));

我在这里模仿了演示:https ://stackblitz.com/edit/angular-xwsltm


推荐阅读