私はAngular2が新しく、JSONファイルのコンテンツをテンプレートにレンダリングするWebアプリケーションを構築するのに苦労しています。私はJSONファイルの内容を解析するために同じメソッドを使用していますが、テンプレートを通してレンダリングする必要があるデータの一部だけを取得しています。アプリケーションの一部に「オブジェクトオブジェクト」が表示され、他の部分には正しいキーが表示されません。したがって、いかなるヒントや助けも非常に高く評価されます。Angular2アプリケーションのJSONオブジェクトをレンダリングすると "object Object"が返されます
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>
何が間違っていますかコードですか?
何がエラーになりますか? –
テンプレート内に「オブジェクトオブジェクト」があります –
正確にJSONをレンダリングしようとしていますか?問題の例を表示できますか?JSON –