【问题标题】:Calling Multiple GET Api in Angular 2在 Angular 2 中调用多个 GET Api
【发布时间】:2018-03-23 07:11:39
【问题描述】:

我创建了一个基本表单,它接收来自用户的值并点击一个 GET API,比如说 GET API1 并以表格格式返回数据。 这是代码:

import { Component } from '@angular/core';
import { Http } from '@angular/http';

import { Hero }    from './hero';

@Component({
  selector: 'hero-form',
  templateUrl: './hero-form.component.html'
})
export class HeroFormComponent {

  model:any = {};

  submitted = false;
  data: any;

  constructor(private http: Http) {}


  onSubmit() { 
    this.submitted = true;
    this.http.get(`http://localhost:8188/data/v1/Api/res/${this.model.config}/${encodeURIComponent(this.model.start)}/${encodeURIComponent(this.model.end)}`)
      .subscribe(response => this.data = response.json());
  }

}

现在,如果我想访问另一个 API,假设 GET API2 具有相同的参数集,那么我该怎么做呢?

编辑:在实际从表单中获取值之前可能是一个逻辑 - 喜欢在 API GET1 或 API GET2 之间进行选择,然后继续使用表单会有所帮助。

【问题讨论】:

    标签: angular rest api http get


    【解决方案1】:

    如果像您提到的那样,用户可以选择要使用的 api 端点,我假设它已绑定到您的模型,因此您可以在函数中使用 this.model.api。或者定义 2 个单独的 url 并在两者之间进行选择。

    let api1 = http://localhost:8188/data/v1/'
    let api2 = http://localhost:8188/data/v2/'
    
    onSubmit() { 
        this.submitted = true;
        this.http.get(api1 + '/res/${this.model.config}/${encodeURIComponent(this.model.start)}/${encodeURIComponent(this.model.end)}`)
          .subscribe(response => this.data = response.json());
      }
    

    如果 api 值存储在模型中。

    onSubmit() { 
        this.submitted = true;
        this.http.get(this.model.api + '/res/${this.model.config}/${encodeURIComponent(this.model.start)}/${encodeURIComponent(this.model.end)}`)
          .subscribe(response => this.data = response.json());
      }
    

    但是,如果您打算进一步开发此功能,并使用更多功能达到不同的 api 端点。然后我建议你创建一个 API 服务。 https://www.sitepoint.com/angular-rxjs-create-api-service-rest-backend/

    【讨论】:

    • 按照第二种方式定义了 2 个单独的 URL 后,您如何选择?
    • 在这个例子中,我只是定义了 2 个单独的 api url。表明你可以做到这一点。您可以轻松地在表单中包含用户选择 api 的内容。所以 api 的值会保存在 this.model.api 中。然后你可以将 api1 换成 model.api 值
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-11-22
    • 2016-10-11
    • 2018-01-05
    • 1970-01-01
    • 1970-01-01
    • 2017-04-24
    • 1970-01-01
    相关资源
    最近更新 更多