Aic*_*ink 7 javascript angular2-services angular
已经和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 btw ..
这是一些代码 - 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);
}
)
;
});
}
}
Run Code Online (Sandbox Code Playgroud)
这是我的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);
})
;
}
}
Run Code Online (Sandbox Code Playgroud)
最后,profile.html模板:
<pre> <!-- works! -->
{{profileUser | json}}
</pre>
Run Code Online (Sandbox Code Playgroud)
要么..
<pre> <!-- throws the error -->
{{profileUser.name | json}}
</pre>
Run Code Online (Sandbox Code Playgroud)
要么..
<pre> <!-- throws the error -->
{{profileUser.name.firstName}}
</pre>
Run Code Online (Sandbox Code Playgroud)
仅供参考,profileUser如下所示:
{
"id": "9830ecfa-34ef-4aa4-86d5-cabbb7f007b3",
"name": {
"firstName": "John",
"lastName": "Doe",
"fullName": "John Doe"
}
}
Run Code Online (Sandbox Code Playgroud)
如果有人可以帮助我,那会很棒,这真的让我回过头来熟悉Angular v2.谢谢!
Thi*_*ier 21
实际上,您的profileUser对象是从HTTP请求加载的,它可以null在开头.该json管只是做了JSON.stringify.
这是你的错误信息所说的:undefined is not an object (evaluating 'l_profileUser0.name').
您需要确保您的profileUser对象不为null才能获取其name属性等等.这可以使用*ngIf指令完成:
<div *ngIf="profileUser">
{{profileUser.name | json}}
</div>
Run Code Online (Sandbox Code Playgroud)
当数据存在时,将显示HTML块.
正如埃里克所说,猫王运营商也可以帮助你.{{profileUser.name | json}}你可以使用而不是拥有{{profileUser?.name | json}}.
希望它对你有帮助,蒂埃里
| 归档时间: |
|
| 查看次数: |
5483 次 |
| 最近记录: |