Angular 2.0 BETA - HTTP请求并显示其属性

时间:2016-01-28 00:19:22

标签: angular angular2-routing angular2-template angular2-services

我们在显示映射到接口的已获取数据时遇到问题。 这三个文件叫做:

  • teacher.service.ts
  • teacher.component.ts
  • teacher.ts

我们获取了一个普通的javascript对象,但我们无法弄清楚如何在模板中显示它。我们尝试使用{{teacher.firstname}} - >进行展示失败并且{{test.firstname}} - >成功即可。 test是手工制作的javascript对象,具有与界面相同的属性(名字,姓氏)。

以下是测试结果+错误消息:

enter image description here

以下是一些代码:

// 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);
    }
}

1 个答案:

答案 0 :(得分:1)

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

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

teacher

2-可以说更好,甚至不要尝试渲染组件,直到你真正为老师提供价值:

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