1
我是Angular的新手,但我一直在爭取這5個小時,無法弄清楚:我無法從Angular4應用中的json請求中獲取對象。 我在我的服務如下功能:無法從json響應獲取對象
getById(id: number) {
return this.http.get('/api/users/' + id, this.jwt()).map((response: Response) => response.json());
}
在我的部分,我有:
export class EditUserComponent implements OnInit {
appUser: User;
id: number;
private sub: any;
ngOnInit(): void {
this.sub = this.route.params.subscribe(params => {
this.id = +params['id']; ;
});
this.userService.getById(this.id).subscribe((appUser: User) => {
this.appUser = appUser;
});
}
constructor(private auth: AuthenticationService, private userService:
UserService, private route: ActivatedRoute,
private location: Location) {
}
}
而且我在HTML視圖中顯示用戶類的屬性,像{{appUser.firstName}}
等。然後我得到ZoneAwareError
:
TypeError: Cannot read property 'firstName' of undefined
at Object.eval [as updateRenderer] (ng:///AppModule/EditUserComponent.ngfactory.js:37:34)
at Object.debugUpdateRenderer [as updateRenderer] (http://localhost:4200/vendor.bundle.js:12856:21)
at checkAndUpdateView (http://localhost:4200/vendor.bundle.js:12235:14)
at callViewAction (http://localhost:4200/vendor.bundle.js:12545:17)
at execComponentViewsAction (http://localhost:4200/vendor.bundle.js:12491:13)
at checkAndUpdateView (http://localhost:4200/vendor.bundle.js:12236:5)
at callWithDebugContext (http://localhost:4200/vendor.bundle.js:13218:42)
at Object.debugCheckAndUpdateView [as checkAndUpdateView] (http://localhost:4200/vendor.bundle.js:12758:12)
at ViewRef_.detectChanges (http://localhost:4200/vendor.bundle.js:10327:63)
at RouterOutlet.activateWith (http://localhost:4200/vendor.bundle.js:32148:42)
at ActivateRoutes.placeComponentIntoOutlet (http://localhost:4200/vendor.bundle.js:31329:16)
at ActivateRoutes.activateRoutes (http://localhost:4200/vendor.bundle.js:31310:26)
at http://localhost:4200/vendor.bundle.js:31246:58
at Array.forEach (native)
at ActivateRoutes.activateChildRoutes (http://localhost:4200/vendor.bundle.js:31246:29)
謝謝!這真的是初學者的錯誤.. – Pawel