在Angular 2中调用多个GET Api

时间:2017-10-11 14:40:08

标签: angular rest api http get

我创建了一个基本表单,它接收来自用户的值并点击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之间进行选择然后继续表单会有所帮助。

1 个答案:

答案 0 :(得分:0)

如果您提到用户可以选择使用哪个api端点,我假设它被绑定到您的模型,那么您可以在您的函数中使用this.model.api。或者定义2个单独的网址并在两者之间进行选择。

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/