0

I just moved my data from mock data to in memory and everything seemed to be fine, except now when I click a button that should create various fields based on the data, they show up completely blank.

app.module.ts

import { BrowserModule }       from '@angular/platform-browser';
import { NgModule }            from '@angular/core';
import { FormsModule }         from '@angular/forms';
import { HttpModule }          from '@angular/http';
import { RouterModule }        from '@angular/router';

// Import for loading in-memory web api
import { InMemoryWebApiModule } from 'angular-in-memory-web-api';
// Important mock data from in memory service
import { InMemoryDataService }  from './in-memory-data.service';


import { AppComponent }        from './app.component';
import { SimXesComponent}      from './simxes.component';
import { SimXComponent }       from './simx.component';
import { SimXDetailsComponent} from './simx-details.component';
import { SimXService }         from './simx.service';

import { AppRoutingModule }     from './app-routing.module';

@NgModule({
  declarations: [
    AppComponent,
    SimXesComponent,
    SimXComponent,
    SimXDetailsComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    InMemoryWebApiModule.forRoot(InMemoryDataService),
    AppRoutingModule
  ],
  providers: [
    SimXService
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

simx.component.html

<!-- SimutronX constructor: takes variables for creating a new Simutron instance -->
<h3>Create SimutronX</h3>
<form>
  <label for="SimX title">SimutronX Title</label>
  <input name="title" type="text" maxlength="2" placeholder="SimutronX" min="1" max="99"><br>
  <label for="coefficients">Number of {{coefficients.title}}</label>
  <input [(ngModel)]="coefficients.value" name="coefficients" type="number" maxlength="2" placeholder="1" min="1" max="99"><br>
  <label for="constraints">Number of {{constraints.title}}</label>
  <input [(ngModel)]="constraints.value" name="coefficients" type="number" maxlength="2" placeholder="1" min="1" max="99"><br>
  <button (click)="inputNums()">Submit</button>
</form>

<form *ngIf="valuesinput">
  <div>
    <label>Coefficient titles:</label>
    <li *ngFor="let slider of onedsliders">
      <input [(ngModel)]="slider.name" [ngModelOptions]="{standalone: true}" type="text" size="30" placeholder="Profit" ><br>
    </li>
    <label>Coefficient values:</label>
    <li *ngFor="let slider of onedsliders">
      <input [(ngModel)]="slider.value" [ngModelOptions]="{standalone: true}" type="text" size="30" placeholder="0" ><br>
    </li>
  </div>
  <div>
    <label>Constraint titles:</label>
    <li *ngFor="let slider of twodsliders">
      <input [(ngModel)]="slider.name" [ngModelOptions]="{standalone: true}" type="text" size="30" placeholder="Product Volume"><br>
    </li>
    <label>Upper boundries (max value)</label>
    <li *ngFor="let slider of twodsliders">
      <input [(ngModel)]="slider.max_value" [ngModelOptions]="{standalone: true}" type="text" size="30" placeholder="Max Product" ><br>
    </li>
    <label>Lower boundries (min value)</label>
    <li *ngFor="let slider of twodsliders">
      <input [(ngModel)]="slider.min_value" [ngModelOptions]="{standalone: true}" type="text" size="30" placeholder="Existing Orders" ><br>
    </li>
  </div>
  <div>
    <label>Objective function title(s):</label>
    <li *ngFor="let output of outputs">
      <input [(ngModel)]="output.name" [ngModelOptions]="{standalone: true}" type="text" size="30" placeholder="Most Profit" ><br>
    </li>
  </div>
  <button (click)="createSimX()">Create SimutronX</button>
  <button (click)="createOneDSliders(5)">Test Button</button>
</form>

<!--  SimutronX instantiates here -->
<div *ngIf="simXcreated">
  <ul class="coefficients">
    <h3 class="header3" id="coefheader">{{coefficients.title}}</h3>
    <li *ngFor="let slider of onedsliders">
      <span class="onedslider">{{slider.id}}</span> {{slider.name}} = value: {{slider.value}}
    </li>
  </ul>
  <ul class="constraints">
    <h3 class="header3" id="consheader">{{constraints.title}}</h3>
    <li *ngFor="let slider of twodsliders">
      <span class="twodslider">{{slider.id}}</span> {{slider.name}} = top value: {{slider.max_value}}, bottom value: {{slider.min_value}}
    </li>
  </ul>
  <ul class="minmaxes">
    <h3 class="header3" id="minmaxheader">min/max</h3>
    <li *ngFor="let switch of switches">
      <span class="switch">{{switch.id}}</span> {{switch.name}} = state:
      <span *ngIf="switch.onoff" class="on"> on</span>
      <span *ngIf="!switch.onoff" class="off"> off</span>
    </li>
  </ul>
  <ul class="objectivefunctions">
    <h3 class="header3" id="objfuncheader">objective function</h3>
    <li *ngFor="let output of outputs">
      <span class="outputs">{{output.id}}</span> {{output.name}} = value: {{output.value}}
    </li>
  </ul>
</div>

in-memory-data.service

import { InMemoryDbService } from 'angular-in-memory-web-api';
import { UIConstructor, s_OneDSlider, s_TwoDSlider, s_Switch, s_Output } from './gui';
import { SimX } from './simx';

export class InMemoryDataService implements InMemoryDbService {
  createDb() {
    let simxes: SimX[] = [
    { id: 1, title: "Person Simulator",
      num_onedsliders: 3, num_twodsliders: 5, num_switches: 1,
      num_outputs: 1, onedslider_names: ["Herbert, Gwen", "Fred"],
      twodslider_names: ["Big Int", "Lead Reduction Variable",
      "Overhead", "Muscle Cramp", "Perculiarity Factors"],
      switch_names: ["Max/Min"],
      output_names: ["Profit"]
    },
    { id: 2, title: "Logistics",
      num_onedsliders: 2, num_twodsliders: 2, num_switches: 1,
      num_outputs: 1, onedslider_names: ["Kettlebells", 'Beans'],
      twodslider_names: ["Row Reduction", "Moon Phase" ],
      switch_names: ["Max/Min"],
      output_names: ["Objective Function"]
    }
  ];

  let s_onedsliders: s_OneDSlider[] = [
    { id: 1, name: 'Shipping Container Purchase Cost', value: 7, quantity: 9 },
    { id: 2, name: 'Container Rental Costs', value: 99, quantity: 15 }
  ];
  let s_twodsliders: s_TwoDSlider[] = [
    { id: 1, name: 'Available Shipping Containers', max_value: 99, min_value: 0, quantity: 3 },
    { id: 2, name: 'Purchasing Staff Available', max_value: 82, min_value: 0, quantity: 5 }
  ];
  let s_switches: s_Switch[] = [
    { id: 1, name: 'Min/Max', state: true }
  ];
  let s_output: s_Output[] = [
    { id: 1, name: 'Profit', value: 1000 }
  ];

  return {simxes, s_onedsliders, s_twodsliders, s_switches, s_output};
  }
}

simx.component.ts

import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';

import { UIConstructor, s_OneDSlider, s_TwoDSlider, s_Switch, s_Output } from './gui';
import { SimXService } from './simx.service';
import { SimX } from './simx';

@Component({
  selector: 'simx',
  templateUrl: './simx.component.html',
  styleUrls: ['./simx.component.css'],
  providers: [SimXService]
})

export class SimXComponent implements OnInit {
  simxes: SimX[];
  s_onedsliders: s_OneDSlider[];
  s_twodsliders: s_TwoDSlider[];
  s_switches: s_Switch[];
  s_outputs: s_Output[];
  valuesinput = false;
  simXcreated = false;

  ngOnInit(): void {
  }

  constructor(private router: Router,
              private simXService: SimXService) { }

  // Defines constructor values
  coefficients: UIConstructor = {
    id: 1,
    title: 'coefficients',
    value: 2
  }
  constraints: UIConstructor = {
    id: 1,
    title: 'constraints',
    value: 2
  }
  // Placeholders --  unhide hidden elements
  inputNums(): void {
    this.valuesinput = true;
  }
  createSimX(): void {
    this.simXcreated = true;
  }

  // Get all already created SimutronXes
  getSimXes(): void {
    this.simXService.getSimXes()
        .then(simxes => {
          this.simxes = simxes;
    });
  }



  /* Get GUI elements */
  getOneDSliders(): void {
    this.simXService.getOneDSliders()
        .then(sliders => {
          this.s_onedsliders = sliders;
    });
  }
  getTwoDSliders(): void {
    this.simXService.getTwoDSliders()
        .then(sliders => {
          this.s_twodsliders = sliders;
    });
   }
   getSwitches(): void {
    this.simXService.getSwitches()
          .then(switches => {
          this.s_switches = switches;
      });
   }
   getOutputs(): void {
     this.simXService.getOutputs()
         .then(outputs => {
           this.s_outputs = outputs;
     });
   }

   /* Create GUI elements in the DOM */
   createOneDSliders(num: number): void {
     for(let i = 0; i < num; i++) {
       console.log(this.s_onedsliders);
       console.log(this.getOneDSliders());
     }
   }
   createTwoDSliders(num: number): void {
     for(let i = 0; i < num; i++) {
       this.getTwoDSliders();
     }
   }
   createSwitches(num: number): void {
     for(let i = 0; i < num; i++) {
       this.getSwitches();
     }
   }
   createOutputs(num: number): void {
     for(let i = 0; i < num; i++) {
       this.getOutputs();
     }
   }

}

simx.ts

export class SimX {
  id: number;
  title: string;
  num_onedsliders: number;
  num_twodsliders: number;
  num_switches: number;
  num_outputs: number;
  onedslider_names: Array<string>;
  twodslider_names: Array<string>;
  switch_names: Array<string>;
  output_names: Array<string>;
}

I tried running some console.log tests and the results were quite strange. When I first ran the test, (you can see the console.log statement in simx.component.ts) all of the in memory variables output as undefined. Yet when I clicked the button again, the output was [object object] and the details were of the in memory service data.

Why is this happening?

2
  • Just remarking that you should not name methods with a get prefix if they don't return a value. Commented May 5, 2017 at 21:32
  • 1
    Some of the methods aren't finished yet. I said I am utterly exhausted and haven't had energy to edit properly yet but it was edited out by a high rep user. Commented May 5, 2017 at 21:44

1 Answer 1

1

You don't show your service, but I assume now that you are using the in-memory web API that your retrieval methods are asynchronous.

I would assume that is why are you seeing it behave differently than with hard-coded data. The values will be undefined until they are retrieved.

I have an example of CRUD using the in-memory web API here if you are interested in an example: https://github.com/DeborahK/Angular2-ReactiveForms/tree/master/APM-Updated

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.