加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

Angular 2:多个HTTP服务

发布时间:2020-12-17 10:33:57 所属栏目:安全 来源:网络整理
导读:我们在项目中使用Angular 2.到目前为止,我们在开发中的数据服务中使用了in-memory-web-api: app.module.ts: imports: [ HttpModule,InMemoryWebApiModule.forRoot(MockData),...] data.service.ts: constructor(private http: Http) { } 现在是时候获取一
我们在项目中使用Angular 2.到目前为止,我们在开发中的数据服务中使用了in-memory-web-api:

app.module.ts:

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

data.service.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”,角度在内存web-api提供了几个选项.

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

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

这将做的是将任何无法找到集合的请求转发给真正的XHR.因此,一种选择是逐步从内存数据库中删除集合,如同需要的那样.

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

从数据库中删除狗集合后,内存中现在将所有狗请求转发到真实后端.

这只是一个集合级修复.但是如果你需要更细粒度的控制,你可以使用方法拦截器.

在您的MockData类中,假设您要覆盖get方法,只需使用HttpMethodInterceptorArgs参数将其添加到MockData类.

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(args: HttpMethodInterceptorArgs) {
  return args.passthroughBackend.createConnection(args.requstInfo.req).response
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读