Search code examples
javascriptangularangular-mock

Mock back-end responses in Angular 2


In my application made with Angular 1, I've used angular-mocks to build front-end without requiring the back-end to be up and running:

(function() {
  angular
    .module('myapp')
    .run(['$httpBackend', function($httpBackend) {

      $httpBackend.whenGET(/.*\/api\/ratings\/\?.*/).respond(function(method, url) {
        var params = matchParams(url.split('?')[1]);
        var list = findRatings(ratings, params);
        return createPageResponse(list, params.page, params.size);
      });
    }]
})();

Now I want to do that in Angular 2. What is the recommended way to do that?


Solution

  • Use could use different services depending on some condition:

    @NgModule({
      imports: [..],
      declarations: [..],
      providers: [
        {
           provide: YourService,
           useClass: env.prod ? YourService : DummyService
        }
      ],
      bootstrap: [..]
    })
    export class AppModule {
    
    }
    

    Or with use of a factory, if you need some more complex stuff..

    @NgModule({
      imports: [..],
      declarations: [..],
      providers: [
        AnotherService,
        {
            provide: YourService,
            useFactory: (isProd, anotherSrvc) => isProd ? new YourService(anotherSrvc) : new DummyService(),
            deps: [env.prod, AnotherService]
        }
      ],
      bootstrap: [..]
    })
    export class AppModule {
    
    }