Angular 2:多个 HTTP 服务

2023-11-23

我们在项目中使用 Angular 2。到目前为止我们使用in-memory-web-api在我们开发中的数据服务中:

应用程序模块.ts:

imports: [
    HttpModule,
    InMemoryWebApiModule.forRoot(MockData),
    ...
]

数据服务.ts:

constructor(private http: Http) { }

现在是时候获取一些真实数据了。但是,我们无法一次性全部替换 Mock Data。如何将我的数据服务配置为:

constructor(private fakeHttp: FakeHttp, /* this one use in-memory-api */
            private http: Http /* this one goes to real remote server */) { }

这样我们就可以随着项目的进展逐渐将模拟数据移出?


与其尝试做这个丑陋的“两个 HTTP”,angular-in-memory-web-api提供了几个选项。

从 0.1.3 开始,有一个配置属性可以将所有未找到的集合调用转发到常规 XHR。

InMemoryWebApiModule.forRoot(MockData, {
  passThruUnknownUrl: true
})

其作用是将无法找到集合的任何请求转发到真正的 XHR。因此,一种选择是根据需要逐渐从内存数据库中删除集合。

class MockData implements InMemoryDbService {
  createDb() {
    let cats = [];
    let dogs = [];
    return {
      cats,
      // dogs
    };
  }
}

一旦您删除了dogs从数据库收集后,内存中现在会将所有狗请求转发到真正的后端。

这只是一个集合级别的修复。但如果您需要更精细的控制,则可以使用方法拦截器。

In your MockData类,假设你想覆盖get方法,只需将其添加到MockData类,具有HttpMethodInterceptorArgs争论。

class MockData implements InMemoryDbService {
  get(args: HttpMethodInterceptorArgs) {
    // do what you will here
  }
}

的结构HttpMethodInterceptorArgs如下(只是为了让您知道可以用它做什么)

HttpMethodInterceptorArgs: {
  requestInfo: {
    req: Request (original request object)
    base
    collection
    collectionName
    headers
    id
    query
    resourceUrl
  }
  passThruBackend: {
    The Original XHRBackend (in most cases)
  }
  config: {
    this is the configuration object you pass to the module.forRoot
  }
  db: {
    this is the object from creatDb
  }
}

举个例子,如果您刚刚转发了所有 get 请求,情况如下

get(args: HttpMethodInterceptorArgs) {
  return args.passthroughBackend.createConnection(args.requstInfo.req).response
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Angular 2:多个 HTTP 服务 的相关文章

随机推荐