【问题标题】:How to implement common interface for multiple API?如何实现多个 API 的通用接口?
【发布时间】:2017-12-29 17:29:28
【问题描述】:

我已经为我的应用程序实现了 RestAPI。现在我正在尝试使用 Angular 开发前端应用程序。每个 RestAPI 返回一个单独的 JSON 对象。除了为每个 http 请求实现对单个 RestAPI 的每次调用之外,有没有办法实现一个接口来很好地进行 RestAPI 调用?具体如下,

this.http.get('http://a.b.c/api/people/1').subscribe(json => makePerson(json));
this.http.get('http://a.b.c/api/animal/1').subscribe(json => makeAnimal(json));
this.http.get('http://a.b.c/api/flower/1').subscribe(json => makeFlower(json));

这里有两种不同的方法,但是我可以通过传入 API URL 和类名来生成一个接口来包含这 3 个方法调用吗?

this.call_restapi(url, 'Person');
this.call_restapi(url, 'Animal');
this.call_restapi(url, 'Flower');

您能否就此提供一些想法?

【问题讨论】:

    标签: angular interface endpoints


    【解决方案1】:

    您可以在订阅者中添加 switch 语句,并使用参数来导航 GET 请求和 switch 语句。

      get(type: string) {
        const url: string = 'http://a.b.c/api/' + type + '/1';
        this.http.get(url).subscribe(
        (json) => {
          switch(type) {
            case('people'):
              this.makePerson(json));
              break;
            case('animal'):
              this.makeAnimal(json));
              break;
            case('flower'):
              this.makeFlower(json);
              break;
            default:
              break;
          }
    
        });
      }
    

    【讨论】:

    • 哇!更进一步,有没有什么方法可以在没有任何限制的情况下处理这个问题?我的意思是我不想在 api url 中添加任何规则。我只想从传入的同一个 api url 接收 JSON 对象。这个问题的要点与有一种方法可以用变量动态创建对象更相关?
    • 我不这么认为,但假设有可能,这听起来不是一个理想的解决方案,因为它可能导致处理过于复杂。也许你想多了你的问题,这里真正的最终目标是什么?
    • 我在想的是,我创建的地图的键和值分别是类名(“人”、“动物”、“花”)和对象类型(人、动物、花)。返回的 JSON 对象将根据传入的类名映射到相应的对象。所以,我想避免实现单独的 RestAPI 调用。我只想解决一个功能。这很奇怪吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-10-03
    • 1970-01-01
    • 1970-01-01
    • 2019-10-12
    • 2016-09-09
    • 2022-11-18
    • 2021-11-18
    相关资源
    最近更新 更多