【问题标题】:Angular2 - Where can be endpoints configured using InMemoryWebApiModule?Angular2 - 在哪里可以使用 InMemoryWebApiModule 配置端点?
【发布时间】:2018-05-06 05:07:04
【问题描述】:

我在关注this tutorial(Angular2官方“快速入门”教程)

最后,有几个 http 请求(GET、POST、PUT、DELETE...),它们不是调用真实服务器,而是使用app.module.ts 中的以下行进行模拟:

// The HttpClientInMemoryWebApiModule module intercepts HTTP requests
// and returns simulated server responses.
// Remove it when a real server is ready to receive requests.
HttpClientInMemoryWebApiModule.forRoot(
  InMemoryDataService, { dataEncapsulation: false }
)

以下是应用程序发出的 HTTP 请求示例:

  private heroesUrl = 'api/heroes';  // URL to web api

  /** GET heroes from the server */
  getHeroes (): Observable<Hero[]> {
    return this.http.get<Hero[]>(this.heroesUrl)
      .pipe(
        tap(heroes => this.log(`fetched heroes`)),
        catchError(this.handleError('getHeroes', []))
      );
  }

问题:有没有办法配置这个 InMemoryDataService 所期望的端点?因此,例如,我可以将 Url 更改为 api/heroes/getAll

【问题讨论】:

  • 我认为 this 是你要找的。​​span>

标签: angular http local-storage angular2-services endpoint


【解决方案1】:

根据@Szarik 的建议,我关注this link,它有答案。实际上,这是我正在使用的库的官方规范:in-memory-web-api

在 README.md 中稍微深入一下,我们会看到:

您可以通过在 InMemoryDbService 中实现 parseRequestUrl 方法来覆盖默认解析器。

服务使用两个参数调用您的方法。

  1. url - 请求的 URL 字符串
  2. requestInfoUtils - RequestInfoUtilities 对象中的实用程序方法,包括默认解析器。请注意,某些值尚未设置,因为它们取决于解析结果。

您的方法必须返回 ParsedRequestUrl 对象或 null|undefined,在这种情况下,服务使用默认解析器。通过这种方式,您可以拦截和解析一些 URL,而将其他 URL 留给默认解析器。

原来如此!

【讨论】:

    【解决方案2】:

    以上面的答案为例: “forRoot”采用可选设置,其中有一个“apiBase”。匹配一个端点

    private url = '/some/endpoint/responseExample';

    设置对应的'apiBase'不带前缀和后缀斜杠:

        HttpClientInMemoryWebApiModule.forRoot(InMemoryDbItemService, { apiBase: 'some/endpoint'})
    
    

    “responseExample”是实际数据。

       createDb() {
        const responseExample = {[some:'structure']}
    
        return { responseExample };
      }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-04-02
      • 1970-01-01
      • 2018-05-12
      • 1970-01-01
      • 2018-05-05
      • 2011-03-14
      • 2018-01-10
      • 2012-05-11
      相关资源
      最近更新 更多