Learn how to call a REST API from your Angular application service and mock it using Mockoon API mocking tools
In this guide, we will learn how to call a REST API from an Angular application. If you already have an existing API that you want to use, you can skip the first step, in which we create a fake REST API using Mockoon.
During the development of your Angular application, you may need to mock an API that is not ready yet, or only partially available (see partial mocking with the proxy mode). For this, the easiest way is to create a mock API using a tool like Mockoon. (Read more about the benefits of API mocking).
To learn more about how to set up your first mock API with Mockoon, head over to the Getting started tutorial.
For the rest of the tutorial, we will use an array of fake blog posts. In Mockoon, create a GET /posts
API endpoint that returns an array of blog posts:
You can use the following JSON as the body returned by the endpoint:
Copy[ { "id": 1, "title": "My first blog post" }, { "id": 2, "title": "My second blog post" } ]
Note that your fake mock server will be available at the following URL: http://localhost:3000
. This is the URL we will need to use in our Angular service.
After creating a mock API endpoint in Mockoon, you can now call it from your Angular service.
To do so, we need to inject and use Angular's HttpClient
:
Copyimport { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; @Injectable() export class PostsService { constructor(private http: HttpClient) {} }
We then need to add a getPosts
method that will return an Observable containing our list of posts:
CopygetPosts(): Observable<{ id: number; title: string }> { return this.http.get('http://localhost:3000/posts'); }
Below is our service after putting the two pieces of code together:
Copyimport { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; @Injectable() export class PostsService { constructor(private http: HttpClient) {} getPosts(): Observable<{ id: number; title: string }[]> { return this.http.get('http://localhost:3000/posts'); } }
In any component where we need to display the list of posts, we can now inject our PostsService
and call our getPosts
method:
Copyimport { Component, OnInit } from '@angular/core'; import { PostsService } from '../services/posts-service.ts'; @Component({ selector: 'app-posts', templateUrl: './posts.component.html' }) export class PostsComponent implements OnInit { constructor(private postsService: PostsService) {} ngOnInit() { // subscribe to the Observable to make the HTTP call this.postsService.getPosts().subscribe((posts) => { // we received our posts! console.log(posts); }); } }
To avoid changing the server URL directly in the Angular service, you can put this URL in Angular's environment files.
You would only need to change your environment.dev.ts
and keep your other environment files and service clean.
Copyexport const environment = { production: false, // Your Mockoon's API URL apiURL: 'http://localhost:3000/' };
This would require the use of environment.apiUrl
in your service(s):
Copyimport { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { environment } from '../environments/environment'; @Injectable() export class PostsService { constructor(private http: HttpClient) {} getPosts(): Observable<{ id: number; title: string }> { return this.http.get(`${environment.apiUrl}/posts`); } }
If you are using Angular CLI's proxy feature, you can also edit the proxy.conf.json
file and set the target
to point to your Mockoon's API:
Copy{ "/api": { "target": "http://localhost:3000", "secure": false } }
Do not forget to add the --proxy-config
flag followed by the path to the proxy.conf.json
file to your ng serve
command, or to add the proxyConfig
option to the serve
target in your angular.json
file:
Copy... "architect": { "serve": { "builder": "@angular-devkit/build-angular:dev-server", "options": { "browserTarget": "your-application-name:build", "proxyConfig": "src/proxy.conf.json" }, ...
Learn how to create multiple responses for an API endpoint and serve them using dynamic rules
Read moreLearn how to simulate webhooks or callbacks in your mock API server to test your application's behavior when receiving asynchronous events from third-party services or APIs.
Read moreLearn how to create your first mock REST API with Mockoon in less than 5 minutes
Read more