angulartypescriptangular-servicesangular-redux

Angular 4 - Save from html template to the mock json DB


Angular 4 application , i have a input text boxes, where values have to be stored from template to the json data , that im using as mock db. I have written services and save function below, but not ablt to save it in the .json file. Idea or help to get it working.

<ng-container *ngFor="let data of displayReasonCodes$ | async;let i = index">
<tr class= "row-break">
 <td>  
    <form>
    <form-group>
  <textbox [readOnly]="isEditable" ngModel="{{data .ReasonCode}}"  name="textbox" ></textbox>
        </form-group>
</form>
</td>
<td>
<form>
<form-group>
 <textbox  [readOnly]="isEditable" ngModel="{{data .Description}}" name="textbox1" ></textbox>
</form-group>
 </form>
  </td>

services.ts
@Injectable()


export class CodesService{ 
    constructor(private httpClient:HttpClient, private apiUrlService : ApiUrlService){}

createReasonCodes(data:IReasonCodes){
        var url = this.apiUrlService.getPostfix("/Codes");
        return this.httpClient.post<IPostHttpResponse>(url,codes);
    }

   COMPONENT.TS
save(){

  let newreasoncodeDefinition: IReasonCodes = this.poolModel.get();

  this.rCodesActions.createCodes(newreasoncodeDefinition).
  subscribe(definitionResponse => {
    if(definitionResponse.responseCode ===1 ){
      console.log("The ReasonCode " + newreasoncodeDefinition.ReasonCode + "Created Successfully");

    }
  })


} 

ReasonCode fromUIModel.ts

poolModel: ReasonCodeFormUIModel;
ngOnInit (){
      this.poolModel = new ReasonCodeFormUIModel();

public get() :IReasonCodes {
    let reasonCodes = new ReasonCodes();
    reasonCodes.Code= this.reasoncode;
    reasonCodes.Description = this.description;
return reasonCodes;
}
}

Solution

  • Do I understand correctly that you have a local .json file that you are reading your data from and that you want to update that data?

    As far as I know, that is not possible. You cannot update a local JSON file. If you want to mock database get/post/put, you could instead consider using the Angular inmemory Web API: https://github.com/angular/in-memory-web-api

    This was set up specifically for this purpose ... to mock a back-end server without needing a backend server.

    Most of my sample applications use it.

    You can see it in action in the Angular documentation here: https://angular.io/tutorial/toh-pt6#simulate-a-data-server