angular2 routing - Angular 2.0 BETA - HTTP Request and displaying its attributes -
we having issues displaying fetched data mapped interface. there these 3 files called:
teacher.service.tsteacher.component.tsteacher.ts
we fetched normal javascript object can't figure out how display in template. tried display {{teacher.firstname}} -> failed , {{test.firstname}} -> succeeded. test javascript object made hand , has same properties(firstname, lastname) interface has.
here test-results + error-messages:
here code:
// teacher.ts export interface teacher { id: number, firstname: string, lastname: string, schools: string[], created_at: string, updated_at: string } // teacher.service.ts import {injectable} 'angular2/core'; import {http, headers, request, requestoptions, requestmethod} 'angular2/http'; import {observable} 'rxjs/observable'; import {teacher} '../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} 'angular2/core'; import {router, routeparams} 'angular2/router'; import {teacherservice} '../services/teacher.service'; import {teacher} '../interfaces/teacher'; import {form_directives} 'angular2/common'; @component({ template: '<h1>{{teacher.firstname}}</h1>' + // can use {{t.firstname}} 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 things server data => this.teacher = data, err => alert(err)); } private log(){ // log function simple click event console.log(this.teacher); console.log(this.test); } }
you assigning value test property synchronously, assigning value teacher asynchrounously. first time angular tries access firstname property of teacher, teacher still undefined, that's why error 1 not other. following solutions this:
1- use elvis operator @eric mentioned:
template: '<h1>{{teacher?.firstname}}</h1>'
2- arguably better, don't try render component until have value teacher:
template: '<h1 *ngif="teacher">{{teacher.firstname}}</h1>'

Comments
Post a Comment