Seit einiger Zeit arbeiten Sie mit Angular v1 und seitdem Angular v2 in die Beta kam, haben Sie damit herumgespielt.Angular 2: {{object}} funktioniert, {{object.child}} löst Fehler aus
Jetzt habe ich dieses Stück Code, aber kann es nicht zur Arbeit bringen, weiß wirklich nicht warum. Irgendwie, wenn ich {{profileUser | json}}
drucke, funktioniert alles gut (profileUser ist ein Objekt).
Aber als ich ein Kind dieses Objekt drucken möchte (zB {{profileUser.name}}
oder {{profileUser.name.firstName}}
), Angular führt den folgenden Fehler:
EXEPTION: TypeError: undefined is not an object (evaluating 'l_profileUser0.name') in [ {{profileUser.name}} in [email protected]:11
. btw ..
Hier ist ein Code
Es ist mir wirklich verwirrend, sollte um nur eine der einfachsten Dinge sein .. Nur mit Typoskript gestartet - ProfileService.ts
:
import { Injectable } from 'angular2/core';
import { Headers } from 'angular2/http';
import { API_PREFIX } from '../constants/constants';
import { AuthHttp } from 'angular2-jwt/angular2-jwt';
import 'rxjs/add/operator/map';
@Injectable()
export class ProfileService {
API_PREFIX = API_PREFIX;
constructor(private _authHttp:AuthHttp) {
}
getProfileData(username:string):any {
return new Promise((resolve, reject) => {
this._authHttp.get(API_PREFIX + '/users/username/' + username)
.map(res => res.json())
.subscribe(
data => {
resolve(data.data);
},
err => {
reject(err);
}
)
;
});
}
}
Und hier ist mein ProfileComponent
:
import {Component, OnInit} from 'angular2/core';
import {RouteParams} from 'angular2/router';
import {ProfileService} from '../../services/profile.service';
@Component({
selector: 'profile',
templateUrl: './components/profile/profile.html',
directives: [],
providers: [ProfileService]
})
export class ProfileComponent implements OnInit {
public username:string;
public profileUser:any;
constructor(private _profileService: ProfileService,
private _params: RouteParams) {
this.username = this._params.get('username');
}
ngOnInit() {
this.getProfileData(this.username);
}
getProfileData(username:string):void {
this._profileService.getProfileData(username)
.then(data => {
this.profileUser = data;
console.log(data);
})
;
}
}
schließlich die profile.html
Vorlage:
<pre> <!-- works! -->
{{profileUser | json}}
</pre>
oder ..
<pre> <!-- throws the error -->
{{profileUser.name | json}}
</pre>
oder ..
<pre> <!-- throws the error -->
{{profileUser.name.firstName}}
</pre>
FYI, die profileUser sieht wie folgt aus:
{
"id": "9830ecfa-34ef-4aa4-86d5-cabbb7f007b3",
"name": {
"firstName": "John",
"lastName": "Doe",
"fullName": "John Doe"
}
}
Wäre toll, wenn mir jemand helfen könnte, aus, Das hält mich wirklich davon ab, mich mit Angular v2 vertraut zu machen. Vielen Dank!
[Elvis operator] sein wird (https : //angular.io/docs/ts/latest/guide/template-syntax.html) –
warum wickelst du es in ein Versprechen BTW? – foxx
Ich habe zuerst nicht gedacht, dass du einfach irgendwas probierst ;-) –