0

I am using a json file to populate data on UI in angular. Is there any way I can make changes to this file from UI. I should be able to do a put/post request to update contents of this file.

Any help would be appreciated.

I use this structure as a datasource to populate on UI, I want to edit this json data through angular.

"events"    : {
    "rows": [
      {
        "id"        : 1,
        "resourceId": "a",
        "name"      : "Meeting #1",
       "startDate" : "2018-02-07 11:00",
        "endDate"   : "2018-02-07 14:00",
        "eventType" : "Meeting",
        "eventColor": "blue"
        }]}
Dev2609
  • 9
  • 1
  • 3

1 Answers1

0

You can do this with json-server !

How I set this up

In terminal:

npm i -D @angular-builders/custom-webpack json-server
ng config projects.<project>.architect.build.builder @angular-builders/custom-webpack:browser
ng config projects.<project>.architect.build.options.customWebpackConfig.path custom-webpack.config.js
ng config projects.<project>.architect.serve.builder @angular-builders/custom-webpack:dev-server
ng config projects.<project>.architect.serve.options.customWebpackConfig.path custom-webpack.config.js

This installs the packages needed and modifies angular.json so we can run the json server in tandem when we run ng serve

Then we need to make two files in the root of project:

  • db.json
  • custom-webpack.config.js

in custom-webpack.config we put

const json = require('json-server');

module.exports = {
  devServer: {
    before: function(app) {
      app.use('/api', json.router('db.json'));
    }
  }
};

In db.json we can put our endpoints, in this case

{
    "users": []
}

Now we can use this in our service

const API = '/api/users/';

@Injectable({
  providedIn: 'root'
})
export class AppService {
  constructor(private http: HttpClient) {}

  get(id: number) {
    return this.http.get(API + id);
  }

  post(user: any) {
    return this.http.post(API, user);
  }
}

Do a post and checkout db.json.

json-server docs: https://www.npmjs.com/package/json-server

Brad Axe
  • 815
  • 7
  • 17