Angular 2: several HTTP services

We use Angular 2 in our projects. So far, we use in-memory-web-apiin our data service in the development of:

app.module.ts

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

data.service.ts

constructor(private http: Http) { }

Now it's time to get some real data. However, we cannot immediately replace Mock Data. How to configure the data service to something like:

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

so that we can gradually move the data layout as the project progresses?

+4
source share
1 answer

Instead of trying to make this ugly "two HTTP", angular-in-memory-web-apiprovides a few options.

Starting with 0.1.3, there is a configuration property for sending all not found collection calls to regular XHR.

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

, , , XHR. , , db in-memory, .

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

dogs , .

. , .

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

Source: https://habr.com/ru/post/1656705/


All Articles