tm1701
tm1701

Reputation: 7601

Angular: prepare dummy data for starting app with 'ng serve'

For testing e.g. responsiveness of data tables, I would like to populate a data table with a lot of entries. Testing responsiveness is then done quickly using 'ng serve'.

How can I detect in an Angular app that the application was started using 'ng serve'?

I would like to show dummy data when the application is started using 'ng serve'.

This is especially useful when loading tables and quick-test functionality attached to data rows.

Upvotes: 0

Views: 2288

Answers (2)

tm1701
tm1701

Reputation: 7601

The answer of @Drenai is great! Thank you!

Based on that answer, you may appreciate below steps to get the json-server integrated with your Angular app. This 'json-server' solution really works like charm!

  1. Get the json server

$ npm install --save json-server

  1. Access the useful documentation. You will learn quickly the power of this nice mock server.

Browse to the json-server git repository

  1. Create a mock-data folder in your project. Do NOT put the mock-files in the assets folder.

  2. Create a mock data JSON file and put it in the folder, e.g. mock-data.json. When you can get LIVE data from your (formal) environment, you can put it in a JSON file like:

    { "your-request-type-1" : { your live data set 1 },

    "your-request-type-2" : { your live data set 2 }, }

  3. Add a simple router file in the folder, e.g. mock-routes.json. Map your URL's to the mock data. You need only a router if you REST url differs from the request.

    { "/api/*": "/$1",

    "/journal/paged/*": "/your-request-type-1",

    "/journals": "/your-request-type-2",

    ... }

  4. Add the json-server to your build environment by adding this line to your package.json file. In this case I assume that your REST server is running on localhost:8080.

"json-server": "json-server mockup-data\mockup-data-for-ng-serve.json --port 8080 --routes mockup-data\mockup-routes.json",

The port you can configure via the environment.ts file or you can set it when you detect port 4200. This is not the best solution, but works pretty safely. You find the port via this variable: +${window.location.port}.

  1. Start the json server: $ npm run json-server

  2. Start your app via 'ng serve'

Upvotes: 0

Drenai
Drenai

Reputation: 12387

I'd advise using json-server (or a basic express server) as a mock API to serve JSON

Then use Angular"s --proxy feature to reroute any API calls to your mock server

This is the preferred/only approach I've seen anywhere I've worked. Defo don't hard code mock data into your application (especially if it's ever going to go into production)

There's a good discussion on this here:

Upvotes: 1

Related Questions