【发布时间】:2016-12-15 08:56:56
【问题描述】:
我目前在使用 Angular 2 时遇到了一些问题。我习惯于为我的一个数据库组件创建详细视图。
到目前为止,一切都很好。我的 JSON 服务正在按预期交付数据。 当我从 subscribe 函数中 console.log 我的结果时,它似乎没问题,但是模板崩溃说“无法从未定义的读取......”
这里是源代码:
import 'rxjs/add/operator/switchMap';
import {Component, OnInit} from "@angular/core";
import {ActivatedRoute, Params} from "@angular/router";
import { Location } from '@angular/common';
import {ComponentTypeService} from "./component-type.service";
import {ComponentType} from "./database_objects";
@Component({
moduleId: module.id,
selector: 'component-type-detail',
templateUrl: 'component-type-detail.component.html'
})
export class ComponentTypeDetailComponent implements OnInit{
componentType: ComponentType;
constructor(
private componentTypeService: ComponentTypeService,
private route: ActivatedRoute,
private location: Location,
) {}
ngOnInit(): void {
this.route.params
.switchMap((params: Params) => this.componentTypeService.getComponentTypeDetails(+params['id']))
.subscribe(comp => {
this.componentType = comp;
console.log(comp);
});
}
goBack(): void {
this.location.back();
}
}
这里是服务代码:
import { Injectable } from '@angular/core';
import {ComponentType} from "./database_objects";
import {Http, Headers} from "@angular/http";
import 'rxjs/add/operator/toPromise';
@Injectable()
export class ComponentTypeService{
private baseUrl = 'http://127.0.0.1:8080/myFirstApp/component-types/'
constructor(private http: Http) {}
getComponentTypes(): Promise<ComponentType[]>{
return this.http.get(this.baseUrl)
.toPromise()
.then(response => response.json().results as ComponentType[])
.catch(this.handleError);
}
getComponentTypeDetails(id: number): Promise<ComponentType>{
const url = `${this.baseUrl}${id}/`;
return this.http.get(url)
.toPromise()
.then(response => response.json() as ComponentType)
.catch(this.handleError);
}
private handleError(error: any): Promise<any> {
console.error('An error occurred', error); // for demo purposes only
return Promise.reject(error.message || error);
}
}
更新
感谢您的所有回答。这是模板缺少 *ngIf="componentType" 这是更新的模板:
<div *ngIf="componentType">
<h2>{{componentType.component_type_name}} details!</h2>
<div>
<label>id: </label>{{componentType.id}}
</div>
<div>
<label>name:</label>
<!--<input [(ngModel)]="componentType.component_type_name" placeholder="name" />-->
</div>
<div *ngIf="componentType.components">
<ul>
<li *ngFor="let component of componentType.components">
{{component}}
</li>
</ul>
</div>
</div>
【问题讨论】:
-
模板代码?
-
您的模板在
ngOnInit之前编译,而您的componentType: ComponentType;在初始级别未定义。