我们在显示映射到界面的获取数据时遇到问题。这三个文件称为:
teacher.service.ts
teacher.component.ts
teacher.ts
我们获取了一个普通的 javascript 对象,但我们不知道如何在模板中显示它。我们尝试使用{{teacher.firstname}}
-> failed和 with {{test.firstname}}
-> succeeded显示。test
是一个手工制作的javascript对象,具有与界面相同的属性(名字,姓氏)。
以下是测试结果 + 错误消息:
这是一些代码:
// teacher.ts
export interface Teacher {
id: number,
firstname: string,
lastname: string,
schools: string[],
created_at: string,
updated_at: string
}
// teacher.service.ts
import {Injectable} from 'angular2/core';
import {Http, Headers, Request, RequestOptions, RequestMethod} from 'angular2/http';
import {Observable} from 'rxjs/Observable';
import {Teacher} from '../interfaces/teacher';
@Injectable()
export class TeacherService {
public constructor(private http:Http) {
}
public searchTeacher(name:string) {
if (name.length >= 2) {
return this.http.get('http://localhost/XXXX/teacher/search/' + name).map(res => res.json());
} else {
return false;
}
}
public getTeacher(id:string) {
return this.http.get('http://localhost/XXXX/teacher/' + id)
.map(res => <Teacher> res.json());
}
}
// teacher.component.ts
import {Component, OnInit} from 'angular2/core';
import {Router, RouteParams} from 'angular2/router';
import {TeacherService} from '../services/teacher.service';
import {Teacher} from '../interfaces/teacher';
import {FORM_DIRECTIVES} from 'angular2/common';
@Component({
template: '<h1>{{teacher.firstname}}</h1>' + // i can use {{t.firstname}} but i can't use {{teacher.firstname}}
'<input type="button" (click)="log()">',
providers: [TeacherService],
directives: [FORM_DIRECTIVES]
})
export class TeacherComponent implements OnInit{
public teacher : Teacher;
public name : string;
public test = {firstname: "Horst", lastname: "peter"}; // Test Object equals normal json-object
constructor(private _routeParams:RouteParams, private _teacherService:TeacherService) {}
ngOnInit(){
let id = this._routeParams.get('id');
return this._teacherService.getTeacher(id).subscribe( // fetch the things from server
data => this.teacher = data,
err => alert(err));
}
private log(){ // log function with a simple click event
console.log(this.teacher);
console.log(this.test);
}
}