我已经使用Angular v1工作一段时间了,自从Angular v2进入测试版以来,一直在尝试。
现在我有了这段代码,但是无法使它正常工作,真的不知道为什么。 不知何故,当我打印{{profileUser | json}}
时,一切都正常(profileUser是一个对象)。
但是当我想要打印该对象的子项(例如{{profileUser.name}}
或{{profileUser.name.firstName}}
)时,Angular会抛出以下错误:
EXEPTION:TypeError:undefined is not an object (evaluating 'l_profileUser0.name') in [ {{profileUser.name}} in ProfileComponent@4:11
.
这真的让我感到困惑,应该是最简单的事情之一...顺便说一句,我刚开始接触TypeScript..
下面是一些代码 - 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);
}
)
;
});
}
}
这里是我的 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);
})
;
}
}
最后,是
profile.html
模板:<pre> <!-- works! -->
{{profileUser | json}}
</pre>
或者...
<pre> <!-- throws the error -->
{{profileUser.name | json}}
</pre>
or..
<pre> <!-- throws the error -->
{{profileUser.name.firstName}}
</pre>
请注意,profileUser的格式如下:
{
"id": "9830ecfa-34ef-4aa4-86d5-cabbb7f007b3",
"name": {
"firstName": "John",
"lastName": "Doe",
"fullName": "John Doe"
}
}
希望有人能帮我,这真的阻碍了我对Angular v2的熟悉。谢谢!
http.get
返回一个可观察对象(类似于承诺但更强大),所以在这里没有必要使用承诺。 这个 回答 可以帮助你。 - Thierry Templier