访问动态JSON对象(Angular和Rxjs)

时间:2018-11-24 03:56:12

标签: javascript html json angular rxjs

我需要帮助来访问一些数据并将其显示在Angular的前端(下面的代码)中,我已经尝试了多种方法,但目前没有任何选择。

问题是我无法在UI中显示此数据并无法正确解析它,为什么会发生这种情况,是因为我不确定如何处理对象本身。您将在响应对象中看到我正在共享这些“锻炼”对象中的一些包含2、3甚至5个对象,而显示多个对象是问题。截至目前,我仅通过硬编码索引值来显示一个,这是不希望的。请参见下面的代码和照片。

image that displays the ui

预期:  用户可以在用户界面中看到多个练习,并且用户界面将适应该日期中存在的对象数量

实际:  因为对象索引被硬编码为[0],而不是获取长度并正确处理,所以只能看到一个练习以及相关的集合和操作次数

想法: 获得对象数组的长度遍历它们并将它们推入数组

响应对象的外观: **

owner_id: "2"

personal_record: false

routine_id: "6"

upload_date: "2018-11-08T00:00:00.000Z"

workout: (4) [{…}, {…}, {…}, {…}]

workout_id: "1544921407"

proto: Object

1:

owner_id: "2"

personal_record: false

routine_id: "7"

upload_date: "2018-11-10T00:00:00.000Z"

workout: (2) [{…}, {…}]

workout_id: "2099633889"

proto: Object

2:

owner_id: "2"

personal_record: false

routine_id: "8"

upload_date: "2018-11-16T00:00:00.000Z"

workout: Array(3)

0: {title: "leg pres", setOne: 88, setOneWeight: 879, setTwo: 766, setTwoWeight: 76976, …}

1: {title: "lunges", setOne: 8989898, setOneWeight: 9087, setTwo: 87, setTwoWeight: 8707, …}

2: {title: "leg press", setOne: 8878787, setOneWeight: 87, setTwo: 8708, setTwoWeight: 87, …}

length: 3

proto: Array(0)

workout_id: "3720835005"

proto: Object

length: 3

角度组件

import { Subscription } from 'rxjs/Subscription';
    import { Component, OnInit, ViewChild, Input, OnDestroy } from '@angular/core';
    import { CalendarComponent } from 'ng-fullcalendar'; //https://www.npmjs.com/package/ng-fullcalendar
    import { Options } from 'fullcalendar';
    import { ActionsService } from '../actions.service';
    import { NgxSmartModalService } from 'ngx-smart-modal';
    import { FormBuilder, FormControl, FormGroup, Validators, FormsModule, FormArray } from '@angular/forms';
    import { Router } from '@angular/router'
    import { Observable } from "rxjs/Observable";
    import 'rxjs/add/operator/catch';
    import 'rxjs/add/operator/map'
    import { Deserializable } from './RoutineDTO';
    import { NgxSpinnerService } from 'ngx-spinner';
    @Component({
    selector: 'app-routine',
    templateUrl: './routine.component.html',
    styleUrls: ['./routine.component.css'],
    providers: [ActionsService]
    })

    export class RoutineComponent implements OnInit {
    private experiment: any
    private eventArray: any;
    private selectedEvent: any;
    private selectedEventTitle: any;
    private selectedEventReps: any;
    private selectedWeight: any;
    private eventObject: any
    private calDate: any;
    private localDate: any;
    private workoutID: any;
    private exerciseArray: any;
    private exerciseOBJ: any;
    private exerciseName: any;
    private bodypartName: any;
    private set_one: any;
    private set_two: any;
    private set_three: any;
    private set_four: any;
    private weight_one: any;
    private weight_two: any;
    private weight_three: any;
    private weight_four: any;
    private uploadDate: any;
    private trainingEventData: any;
    private eventForm: FormGroup;
    private trainingDate: FormGroup;
    private bodyText: string;
    calendarOptions: Options;
    toggleAction: boolean = false;
    displayEvent: any;
    private subscribe: Subscription;
    private usersSession: Array;

    @ViewChild(CalendarComponent) ucCalendar: CalendarComponent;
    constructor(
    private spinner: NgxSpinnerService,
    private _fb: FormBuilder,
    protected eventService: ActionsService,
    public ngxSmartModalService: NgxSmartModalService,
    private router: Router
    ) { }

    ngOnInit() {
    this.spinner.show();
    this.eventService.getEvents()
    .subscribe((data: any) => {
    this.trainingEventData = data;

        this.workoutID = this.trainingEventData.map(function (id) {

          return id.workout_id

        });



        this.uploadDate = this.trainingEventData.map(function (date) {

          return date.upload_date

        });

        //contains workout object

        this.exerciseArray = this.trainingEventData.map(function (routine) {

          return routine.workout

        });



        //get all values instead of just first object do this for object 1,2,3,4,5 ...

        this.bodypartName = this.exerciseArray.map(function (bodypart) {

          return bodypart[0].title

        })



        this.set_one = this.exerciseArray.map(function (set_one) {

          return set_one[0].setOne

        })



        this.set_two = this.exerciseArray.map(function (set_two) {

          return set_two[0].setTwo

        })



        this.set_three = this.exerciseArray.map(function (set_three) {

          return set_three[0].setThree

        })



        this.set_four = this.exerciseArray.map(function (set_four) {

          return set_four[0].setFour

        })



        this.weight_one = this.exerciseArray.map(function (setOneWeight) {

          return setOneWeight[0].setOneWeight

        })



        this.weight_two = this.exerciseArray.map(function (setTwoWeight) {

          return setTwoWeight[0].setTwoWeight

        })



        this.weight_three = this.exerciseArray.map(function (setThreeWeight) {

          return setThreeWeight[0].setThreeWeight

        })



        this.weight_four = this.exerciseArray.map(function (setFourWeight) {

          return setFourWeight[0].setFourWeight

        })

        // convert UTC to local browser time

        this.localDate = this.uploadDate.map(function (newDate) {

          return new Date(newDate)

        })





        let getEvent = [];

        for (let i = 0; i < 10; i++) {



          let workoutID = this.workoutID[i]

          let bodypart = this.bodypartName[i];

          let date = this.localDate[i];

          let setOneReps = this.set_one[i]

          let setTwoReps = this.set_two[i]

          let setThreeReps = this.set_three[i]

          let setFourReps = this.set_four[i]

          let setOneWeight = this.weight_one[i]

          let setTwoWeight = this.weight_two[i]

          let setThreeWeight = this.weight_three[i]

          let setFourWeight = this.weight_four[i]

          let insertEvents = {};



          insertEvents =

            {

              id: workoutID,

              title: bodypart,

              start: date,

              color: 'yellow',   // an option!

              textColor: 'black', // an option!

              setOneReps: setOneReps,

              setTwoReps: setTwoReps,

              setThreeReps: setThreeReps,

              setFourReps: setFourReps,

              setOneWeight: setOneWeight,

              setTwoWeight: setTwoWeight,

              setThreeWeight: setThreeWeight,

              setFourWeight: setFourWeight

            }

          getEvent.push(insertEvents);



        }



        this.calendarOptions = {

          editable: true,

          eventLimit: false,

          header: {

            left: 'prev,next today',

            center: 'title',

            right: 'month,agendaWeek,agendaDay,listMonth'

          },

          events: getEvent

        };



      });



    this.eventForm = this._fb.group({

      repsArray: this._fb.array([

        this.getUnit()

      ])

    });



    this.trainingDate = new FormGroup({

      datePicked: new FormControl('', {

        validators: Validators.required

      })

    });

    }

    clickButton(model: any) {
    this.spinner.show();
    this.addEvent()
    this.displayEvent = model;
    }

    //TODO responsible for the click
    eventClick(calEvent, jsEvent, view) {
    this.spinner.show();
    this.selectedEvent = calEvent.event
    console.log(this.selectedEvent)
    this.eventArray = [];
    let repsArray = [];
    let weightArray = [];

    let EventTitle = this.selectedEvent.title

    let s1r = this.selectedEvent.setOneReps;

    let s2r = this.selectedEvent.setTwoReps;

    let s3r = this.selectedEvent.setThreeReps;

    let s4r = this.selectedEvent.setFourReps;

    repsArray.push(s1r, s2r, s3r, s4r)



    let s1w = this.selectedEvent.setOneWeight;

    let s2w = this.selectedEvent.setTwoWeight;

    let s3w = this.selectedEvent.setThreeWeight;

    let s4w = this.selectedEvent.setFourWeight;

    weightArray.push(s1w, s2w, s3w, s4w)



    this.eventArray.push({ EventTitle, repsArray, weightArray })



    console.log(this.eventArray)

    this.ngxSmartModalService.getModal('trainingEvent').open()

    }

    updateEvent(model: any) {
    alert('updating event')
    model = {
    event: {
    id: model.event.id,
    start: model.event.start,
    end: model.event.end,
    title: model.event.title
    // other params
    },
    duration: {
    _data: model.duration._data
    }
    }
    this.displayEvent = model;
    }

    openModal(id: string) {
    // this.modalService.open(id);
    }

    closeModal(id: string) {

    }

    createEventID() {
    let array = new Uint32Array(10);
    crypto.getRandomValues(array);
    let num = Math.floor(Math.random() * 10 + 1);
    return array[3]
    }

    addEvent() {
    let eventObject = {
    id: this.createEventID(),
    title: this.eventForm.value.bodypart,
    start: this.trainingDate.value.datePicked,
    data: this.eventForm.value
    };
    console.log(eventObject)

    this.ucCalendar.fullCalendar('renderEvent', eventObject)

    this.eventService.updateEvent(eventObject)

      .subscribe(status => {

        console.log('=' + status);

      })

    return event

    }

    private getUnit() {
    return this._fb.group({
    title: [''],
    setOne: [''],
    setOneWeight: [''],
    setTwo: [''],
    setTwoWeight: [''],
    setThree: [''],
    setThreeWeight: [''],
    setFour: [''],
    setFourWeight: [''],
    });
    }

   // Add new row into form
    private addUnit() {
    const control = this.eventForm.controls['repsArray'];
    control.push(this.getUnit());
    }

    //Remove from form on click delete button
    private removeUnit(i: number) {
    const control = this.eventForm.controls['repsArray'];
    control.removeAt(i);
    }
    }

HTML

  

             

             查看会议                

    <mat-accordion>
      <mat-expansion-panel *ngFor="let panel of eventArray">
        <mat-expansion-panel-header>
         <h1> {{panel.EventTitle}} </h1> 
        </mat-expansion-panel-header>

        <mat-list>
          <mat-list-item *ngFor="let repsCount of panel.repsArray" > <i class="material-icons">
            power_input
            </i> <div class="space"></div>Reps: {{repsCount}}
          </mat-list-item>

          <mat-divider></mat-divider>
          <mat-list-item *ngFor= "let weightCount of panel.weightArray"> <i class="material-icons">
            fitness_center
            </i> <div class="space"></div> Weight: {{weightCount}}
          </mat-list-item>

        </mat-list>
      </mat-expansion-panel>
    </mat-accordion>

  </div>
</div>   </ngx-smart-modal> </div>

更新:终于找到了它涉及的解决方案,只是从头开始,然后逐步解决该问题。套件并不是很困难,但是很棘手。

 ngOnInit() {
    this.route.params.subscribe(params => {
      this.username = params['username']; // (+) converts string 'id' to a number
      this.eventService.getEvents(this.username)
        .subscribe((data: any) => {
          this.trainingEventData = data;
          console.log(this.trainingEventData)

          this.uploadDate = this.trainingEventData[0].map(function (date) {
            return date.upload_date
          });

          var allEvents = [];
          $.each(this.trainingEventData[0], function (key, value) {
            var title = value.workout[0].title
            var date = new Date(value.upload_date)
            var personal_record = value.personal_record
            var id = value.workout_id
            var workout = value.workout
            var color = "yellow"
            var textColor = 'black'

            var insertEvents = {};
            insertEvents = {
              title: title,
              id: id,
              personal_record: personal_record,
              workout: workout,
              start: date,
              color: 'yellow',   // an option!
              textColor: 'black', // an option!
            }
            allEvents.push(insertEvents);
          }
          );

          this.calendarOptions = {
            editable: true,
            eventLimit: false,
            header: {
              left: 'prev,next today',
              center: 'title',
              right: 'month,agendaWeek,agendaDay,listMonth'
            },
            events: allEvents
          };
        });

      this.eventForm = this._fb.group({
        repsArray: this._fb.array([
          this.getUnit()
        ])
      });

      this.trainingDate = new FormGroup({
        datePicked: new FormControl('', {
          validators: Validators.required
        })
      });
    })
  }

  clickButton(model: any) {
    this.spinner.show();
    this.addEvent()
    this.displayEvent = model;
  }

  //TODO responsible for the click
  eventClick(calEvent, jsEvent, view) {
    this.selectedEvent = calEvent.event
    var workoutSession = [];

    for (let [key, value] of Object.entries(calEvent.event.workout)) {

      var title = value.title;
      var personal_record = value.personal_record
      var repOne = value.setOne;
      var repTwo = value.setTwo;
      var repThree = value.setThree;
      var repFour = value.setFour;
      var s1w = value.setOneWeight;
      var s2w = value.setTwoWeight;
      var s3w = value.setThreeWeight;
      var s4w = value.setFourWeight;


      var insertEvents = {};
      insertEvents = {
        title: title,
        personal_record: personal_record,
        repOne: repOne,
        repTwo: repTwo,
        repThree: repThree,
        repFour: repFour,
        weightOne: s1w,
        weightTwo: s2w,
        weightThree: s3w,
        weightFour: s4w
      }
      workoutSession.push(insertEvents);
      this.Journal = workoutSession;

    }
    // this.bottomSheet.open(BottomSheetJournal);
    this.ngxSmartModalService.getModal('trainingEvent').open()
  }

0 个答案:

没有答案