why genID() method in In-memory-web-api does not generate an ID?

0

Issue

I used angular-in-memory-web-api to simulate a data server. when I post a new model to add to database, I get an error because of property id, I think that the genId() method in the service does not works. my model is:

export class WorkHouse implements WorkHouseInterface{
  id: number = 0;
  title: string = '';
  code: string = '';
  manager: string = '';
  startDate: Date = new Date();
  endDate: Date = new Date();
  evalUnit: string = '';
}

and, InMemoryDataService is:

@Injectable({
  providedIn: 'root'
})
export class InMemoryDataService implements InMemoryDbService{
  createDb() {
    const workHouses = [{id:1, title: 'work1', code: '523', manager: 'xyz', startDate: new Date(), endDate:new Date(), evalUnit: '1'},
                        {id:2, title: 'work2', code: '345', manager: 'abc', startDate: new Date(), endDate:new Date(), evalUnit: '2'}];
    return {workHouses};
  }

  genId(workHouses: WorkHouse[]): number {
    return workHouses.length > 0 ? Math.max(...workHouses.map(workHouse => workHouse.id)) + 1 : 0;
  }
}

so, when I fill the properties of below new model via a form except property id:

    this.newWorkHouse = {id:0, title:'',code:'',manager:'',startDate:new Date(''),endDate:new Date(''), evalUnit:''};

and post it via calling addWorkHouse method in WorkHouse.service:

  /** POST: add a new workHouse to the server */
  addWorkHouse(workHouse: WorkHouse): Observable<WorkHouse> {
    return this.http.post<WorkHouse>(this.workHouseUrl, workHouse, this.httpOptions).pipe(
      tap((newWorkHouse: WorkHouse) => this.log(`added workHouse w/ id=${newWorkHouse.id}`)),
      catchError(this.handleError<WorkHouse>('addWorkHouse'))
    );
  }

by below code:

this.workHouseService.addWorkHouse(this.newWorkHouse).subscribe(workHouse => {
          this.workHouses.push(workHouse)});

but I get an error, and the model is not saved. I think the genId() method does not generate an unique Id for that model. how can I handle this error?

Solution

define property id as any to accept null or undefined initial value:

export class WorkHouse implements WorkHouseInterface{
  id: any = null;
  title: string = '';
  code: string = '';
  manager: string = '';
  startDate: Date = new Date();
  endDate: Date = new Date();
  evalUnit: string = '';
}

and in the form, initial the newWorkHouse:

    this.newWorkHouse = {id:null, title:'',code:'',manager:'',startDate:new Date(''),endDate:new Date(''), evalUnit:''};

or before post the newWorkHose to the server, assign the null or undefined to to its id property:

this.newWorkHouse.id = null;

consider the if (item.id == undefined) statement in post method in the back-end server of in-memory-web-api to call genId(...) method to generate id:

// Create entity
  // Can update an existing entity too if post409 is false.
  protected post({ collection, collectionName, headers, id, req, resourceUrl, url }: RequestInfo): ResponseOptions {
    const item = this.clone(this.getJsonBody(req));

    // tslint:disable-next-line:triple-equals
    if (item.id == undefined) {
      try {
        item.id = id || this.genId(collection, collectionName);
      } catch (err) {
        const emsg: string = err.message || '';
        if (/id type is non-numeric/.test(emsg)) {
          return this.createErrorResponseOptions(url, STATUS.UNPROCESSABLE_ENTRY, emsg);
        } else {
          console.error(err);
          return this.createErrorResponseOptions(url, STATUS.INTERNAL_SERVER_ERROR,
            `Failed to generate new id for '${collectionName}'`);
        }
      }
    }
    
    //......

Answered By – R. Nourmandi

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave A Reply

Your email address will not be published.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More