Using a mock backend for HTTP calls - lordoftheflies/angular-essential-training GitHub Wiki
To work with HTTP calls from Angular you typically need some sort of endpoint to call to but since Angular has a powerful dependency injection engine and the codebase is built upon it, we can actually leverage that to replace Angular's HttpXhrBackend class that handles the HTTP calls and set up a mock one to simulate those calls. The project code has already been setup with a mock class for that. If you are interested in it, feel free to check out the mock-xhr-backend.ts file to see what it's up to. This class is setup to support HTTP calls to the URL 'mediaitems' for get, post and delete verbs. It will allow us to build out the media item service to use Angular's HTTP service while not requiring a separate API to hit. And with Angular's DI architecture, the default HttpXhrBackend class can be replaced with this mock class. Over in the app.module.ts file, we need to import the type that we are going to mock. The HttpXhrBackend. That comes from @angular/common/http. So we can add HttpXhrBackend to the import list. And we need to import the mock one, so we can add an import statement to bring in the MockXhrBackend type. And then we can add a new provide object literal to the providers metadata property for the ngModel decorator. And we can set the provide property to HttpXhrBackend and another property named usedClass. Setting that to the MockXhrBackend. So when some code ask for an HttpXhrBackend it will get an instance of the MockXhrBackend. With this wired up, we can work with the HTTP service in our code and under the hood it will be calling this mock backend, which will handle read and write of media items to an internal list, much like the current media item service does.