Reputation: 530
I am new to Angular2 and pretty much stuck in building a web application that renders the content of a JSON file into a template. I am using the same methods to parse the content of the JSON files, but I am getting just part of the data that I need rendered through the template. Some part of the application shows "object Object", other parts do not show the right key. Therefore, any hints or help would be very much appreciated.
Here´s the search component:
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 the search service:
// 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());
}*/
}
Here are the templates:
first 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>
What is wrong with the code?
Upvotes: 0
Views: 728
Reputation: 4553
I'll go out on a limb here and assume this is where at least one of your problems is occurring.
<li *ngFor="let vehicle of vehicles">
<input type="text" class="form-control" name="vehicles" [(ngModel)]="vehicles">
</li>
You're binding the vehicles
array to each input
element inside an *ngFor
. You need to change it to something like this:
<li *ngFor="let vehicle of vehicles">
<input type="text" class="form-control" name="vehicle-name" [(ngModel)]="vehicle.name">
</li>
Upvotes: 2
Reputation: 5071
It depends in what variable is output as object Object
.
Generally this will be output if the variable you want to print is not a primitive or string but an object.
You should check you data structure.
Upvotes: 1