0

我们在显示映射到界面的获取数据时遇到问题。这三个文件称为:

  • 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);
    }
}
4

1 回答 1

1

您正在test同步地为属性分配一个值,但您正在teacher异步地为该属性分配一个值。所以角度第一次尝试访问 , 的firstname属性仍然是未定义的teacherteacher这就是为什么你得到一个错误而不是另一个错误的原因。以下是一些解决方案:

1-使用像@Eric提到的elvis运算符:

template: '<h1>{{teacher?.firstname}}</h1>'

2-可以说更好,在您真正为教师提供价值之前,甚至不要尝试渲染组件:

template: '<h1 *ngIf="teacher">{{teacher.firstname}}</h1>'

于 2016-01-28T00:52:57.407 回答