2016-09-23 3 views
0

Я новичок в Angular2 и довольно сильно застрял в создании веб-приложения, которое отображает содержимое файла JSON в шаблон. Я использую те же методы для синтаксического анализа содержимого файлов JSON, но я получаю только часть данных, которые мне нужно сделать через шаблон. В некоторой части приложения отображается «объект объекта», другие части не отображают правильный ключ. Поэтому любые подсказки или помощь были бы очень оценены.Рендеринг объекта JSON в приложении Angular2 «Объект объекта»

Here's поиска компонентов:

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') 
    ); 
    } 

} 

Here's поиска услуг:

// 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> 

Что не так wi й код?

+0

Какая ошибка вы получаете? –

+0

Я получаю «объект объекта» в шаблонах –

+1

Где именно вы пытаетесь отобразить JSON? Можете ли вы показать пример проблемы JSON –

ответ

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

Это зависит от того, какая переменная выводится как object Object. Обычно это будет выводиться, если переменная, которую вы хотите распечатать, не является примитивной или строкой, а объектом.
Вы должны проверить структуру данных.

Смежные вопросы