2016-09-23 4 views
0

저는 Angular2를 처음 사용하여 JSON 파일의 내용을 템플릿으로 렌더링하는 웹 응용 프로그램을 작성하는 데 상당히 어려움을 겪고 있습니다. JSON 파일의 내용을 파싱하는 데 동일한 메소드를 사용하고 있지만 템플릿을 통해 렌더링해야하는 데이터의 일부만 가져오고 있습니다. 응용 프로그램의 일부 부분에 "개체 개체"가 표시되고 다른 부분에는 올바른 키가 표시되지 않습니다. 따라서 힌트 나 도움을 주시면 대단히 감사하겠습니다.Angular2 응용 프로그램에서 JSON 객체를 렌더링하면 "객체 객체"가 발생합니다.

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> 

무엇이 잘못 되었습니까? 코드?

+0

무엇이 오류입니까? –

+0

템플릿에서 "object Object"를 얻습니다. –

+1

정확히 JSON을 렌더링하려고합니까? JSON 문제의 예를 보여줄 수 있습니까? –

답변

2

나는 여기서 사지에 나가서 이것이 적어도 하나의 문제가 발생하는 곳이라고 가정합니다.

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

당신은 *ngFor 내부의 각 input 요소에 vehicles 배열을 결합하고 있습니다. 다음과 같이 변경해야합니다.

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

어떤 변수가 출력 되느냐는 object Object입니다. 일반적으로 인쇄하려는 변수가 원시 또는 문자열이 아니라 객체 인 경우이 값이 출력됩니다.
데이터 구조를 확인해야합니다.

관련 문제