在Angular2应用程序中渲染JSON对象导致“对象对象”

时间:2016-09-23 21:33:14

标签: javascript json angular

我是Angular2的新手,并且几乎坚持构建一个将JSON文件的内容呈现为模板的Web应用程序。我使用相同的方法来解析JSON文件的内容,但我只是获得了我需要通过模板呈现的数据的一部分。应用程序的某些部分显示“对象对象”,其他部分未显示正确的键。因此,非常感谢任何提示或帮助。

这是搜索组件:

import { Component, Input, Output, NgModule, EventEmitter, OnInit } from '@angular/core';
import  { AppState } from '../app.service';
import { HomeService } from  '../home/home.service';
import { Item } from './item';
import { SearchService } from './search.service';
import { Observable } from 'rxjs/Observable';


@Component({
  // Selector for search component
  selector: 'search',  //
  // Dependencies for Search component
  providers: [
    HomeService,
    SearchService
  ],
  // Our list of styles in our component. We may add more to compose many styles together
  styleUrls: [],
  // Every Angular template is first compiled by the browser before Angular runs it's compiler
  templateUrl: 'search.template.html'
})
export class Search implements OnInit {

  constructor(private _searchService: SearchService, public appState: AppState, private homeService: HomeService) {
  }

  public tasks;
  public task_types;
  public repair_sites;
  public rails;
  public vehicles;

  public Items: Item [];


  @Output() addVehicle = new EventEmitter();
  // Set our default values
  localState = {value: ''};
  /*vehicles = [
   {
   id: 0,
   name: 'TEST'
   }
   ];*/

  @Output() addAllocation = new EventEmitter();
  // Set our default values
  //localState = { value: '' };
  allocations = [
    {
      id: 0,
      name: 'TEST'
    }
  ];

  @Output() addRail = new EventEmitter();
  // Set our default values
  //localState = { value: '' };
  /*rails = [
   {
   id: 0,
   name: 'TEST'
   }
   ];*/
  @Output() addToGantt = new EventEmitter();
  // Set our default values
  //localState = { value: '' };


  @Output() getFromAPI = new EventEmitter();
  // Set our default values
  //localState = { value: '' };


  @Output() search = new EventEmitter();
  // Set our default values
  //localState = { value: '' };


  // this.appState.set('value', value);


  add(_event) {
    console.log('adding vehicle', _event);
    this.addVehicle.emit({
      value: _event
    });
  }

  ngOnInit() {
    console.log('hello `Home` component');
    //this.getAllItems();
    this.getTasks();
    this.getVehicles();
    this.getRepairSites();
  }

  /*
   private getAllItems():
   void {
   this._searchService
   .GetAll()
   .subscribe((data: Item[]) => this.Items = data,
   error => console.log(error),
   () => console.log('Get all Items complete'));
   }

   @Input()
   item: Item;
   // Every Angular template is first compiled by the browser before Angular runs it's compiler
   //templateUrl: 'search.template.html'
   */

  // Getter and Setter for Tasks
  //TODO: Generalize the getter and setter methods

  getTasks() {
    this._searchService.getTasks().subscribe(
      // the first argument is a function which runs on success
      data => {
        this.tasks = data
      },
      // the second argument is a function which runs on error
      err => console.error(err),
      // the third argument is a function which runs on completion
      () => console.log('done loading tasks')
    );
  }

  setTasks(name) {
    let tasks = {name: name};
    this._searchService.setTasks(tasks).subscribe(
      data => {
        // refresh the list
        this.getTasks();
        return true;
      },
      error => {
        console.error("Error saving task!");
        return Observable.throw(error);
      }
    );
  }

  updateTasks(tasks) {
    this._searchService.updateTasks(tasks).subscribe(
      data => {
        // refresh the list
        this.getTasks();
        return true;
      },
      error => {
        console.error("Error saving task!");
        return Observable.throw(error);
      }
    );
  }

  deleteTasks(tasks) {
    if (confirm("Are you sure you want to delete " + tasks.name + "?")) {
      this._searchService.deleteTasks(tasks).subscribe(
        data => {
          // refresh the list
          this.getTasks();
          return true;
        },
        error => {
          console.error("Error deleting task!");
          return Observable.throw(error);
        }
      );
    }
  }

  getVehicles() {
    this._searchService.getVehicles().subscribe(
      // the first argument is a function which runs on success
      data => {
        this.vehicles = data
      },
      // the second argument is a function which runs on error
      err => console.error(err),
      // the third argument is a function which runs on completion
      () => console.log('done loading vehicles')
    );
  }

  getRepairSites() {
    this._searchService.getRepairSites().subscribe(
      // the first argument is a function which runs on success
      data => {
        this.repair_sites = data
      },
      // the second argument is a function which runs on error
      err => console.error(err),
      // the third argument is a function which runs on completion
      () => console.log('done loading repair sites')
    );
  }

}

以下是搜索服务:

// Necessary imports for Search service

import { Injectable } from '@angular/core';
import 'rxjs/add/operator/map'
import { Observable } from 'rxjs/Observable';
import { Http, Response, Headers, RequestOptions } from "@angular/http";
import 'rxjs/add/observable/forkJoin';
import 'rxjs/add/observable/of';
import { Item } from './item';


@Injectable()
export class SearchService {

  // HTTP constructor

  constructor(private http: Http) {
  }

  // JSON Getter from JSON files
  // Uses http.get() to load a single JSON file
  // TODO: Refactor against real API

  getTasks() {
    return this.http.get('./app/search/tasks.json').map((res: Response) => res.json());
  }

  getTaskTypes() {
    return this.http.get('./app/search/task_types.json').map((res: Response) => res.json());
  }

  getRepairSites() {
    return this.http.get('./app/search/repair_sites.json').map((res: Response) => res.json());
  }

  getVehicles() {
    return this.http.get('./app/search/vehiclegroups.json').map((res: Response) => res.json());
  }


  // Uses Observable.forkJoin() to run multiple concurrent http.get() requests.
  // The entire operation will result in an error state if any single request fails.

  // Method implementation for real API calls

/*
   getVehicles(vehicles) {
   let headers = new Headers({'Content-Type': 'application/json'});
   let options = new RequestOptions({headers: headers});
   let body = JSON.stringify(vehicles);
   // Note: This is only an example. The following API call will fail because there is no actual API to talk to.
   return this.http.get('./app/search/vehiclegroups.json', body, headers).map((res: Response) => res.json());
   }

*/

// CRUD methods for Tasks
// TODO: make abstract


  setTasks(tasks) {
    let headers = new Headers({'Content-Type': 'application/json'});
    let options = new RequestOptions({headers: headers});
    let body = JSON.stringify(tasks);
    // Note: This is only an example. The following API call will fail because there is no actual API to talk to.
    return this.http.post('/api/tasks/', body, headers).map((res: Response) => res.json());
  }

  updateTasks(tasks) {
    let headers = new Headers({'Content-Type': 'application/json'});
    let options = new RequestOptions({headers: headers});
    let body = JSON.stringify(tasks);
    // Note: This is only an example. The following API call will fail because there is no actual API to talk to.
    return this.http.put('/api/tasks/' + tasks.id, body, headers).map((res: Response) => res.json());
  }

  deleteTasks(tasks) {
    // Note: This is only an example. The following API call will fail because there is no actual API to talk to.
    return this.http.delete('/api/tasks/' + tasks.id);
  }


  /*
    getAllItems() {
      let headers = new Headers({'Content-Type': 'application/json'});
      let options = new RequestOptions({headers: headers});
      let body = JSON.stringify(tasks);
      // Note: This is only an example. The following API call will fail because there is no actual API to talk to.
      //return this.http.get('http://10.43.126.73:8060/ppms4/api/tasks/', body, headers).map((res: Response) => res.json());
    }*/
}

以下是模板:

第一个template.html

<div class="scroll scroll4 -webkit-scrollbar-track -webkit-scrollbar-thumb">
  <header class="palette"><h4>Headline</h4></header>
  <form class="form-inline">
    <div class="form-group">
        <ul>
          <li *ngFor="let vehicle of vehicles"><input type="text" class="form-control" name="vehicles" [(ngModel)]="vehicles">
          </li>
        </ul>
        </div>
    </form>
</div>

<div class="scroll scroll4 -webkit-scrollbar-track -webkit-scrollbar-thumb">
  <header class="palette"><h4>Bereitstellungsleistungen</h4></header>
     <form class="form-inline">
      <div class="form-group">
      <ul>
          <li *ngFor="let repair_site of repair_sites"><input type="text" class="form-control" name="repair_sites-name"
                                                              [(ngModel)]="repair_site.name">
          </li>
        </ul>
        <ul>
          <li *ngFor="let task_type of task_types"><input type="text" class="form-control" name="task_types-name"
                                                          [(ngModel)]="task_type.name">
          </li>
          <ul>
            <li *ngFor="let task of tasks"><input type="text" class="form-control" name="task-name" [(ngModel)]="task.name">
             </li>
          </ul>
        </ul>
        </div>
    </form>
</div>

代码有什么问题?

2 个答案:

答案 0 :(得分:2)

我会在这里走出困境,并假设至少有一个问题发生在这里。

<li *ngFor="let vehicle of vehicles">
  <input type="text" class="form-control" name="vehicles" [(ngModel)]="vehicles">
</li>

您将vehicles数组绑定到input内的每个*ngFor元素。您需要将其更改为以下内容:

<li *ngFor="let vehicle of vehicles">
  <input type="text" class="form-control" name="vehicle-name" [(ngModel)]="vehicle.name">
</li>

答案 1 :(得分:1)

取决于输出的变量object Object。 通常,如果要打印的变量不是基元或字符串而是对象,则会输出 你应该检查你的数据结构。

相关问题