2017-05-03 156 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