2017-05-03 155 views
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) 

回答

2

当你的看法首先显示,该组件尚未检索到的数据。这就是appUser未定义的原因。有几种方法可以防止此错误:

1)将appUser初始化为某种东西,以便它不是未定义的。这对您的应用程序的业务规则可能没有意义。

2)在您的视图的某个顶级HTML元素(如<div>)中添加一个*ngIf = "appUser"。这将阻止在检索数据之前显示视图。

3)添加安全导航操作上appUser这样的:{{appUser?.firstName}}这种方法的主要问题是,你需要将它添加到您的页面上的每个使用的appUser

+0

谢谢!这真的是初学者的错误.. – Pawel