11
組件的財產採取用戶從服務中使用參數未捕獲的(在承諾):錯誤:無法讀取未定義
@Component({
selector: 'users',
providers: [UserService],
template: `
<p>{{user.id}}</p>
`
})
export class UserPageComponent implements OnInit {
constructor(
private userService: UserService,
private route: ActivatedRoute
) {};
ngOnInit(): void {
this.route.params.forEach((params: Params) => {
let id = +params['id'];
this.userService.getUser(id)
.then(user => {console.log(user.id);this.user = user})
});
}
服務:
@Injectable()
export class UserService {
private postUrl = 'http://127.0.0.1:8000/user-detail/'; // URL to web api
constructor(private http: Http) {
}
getUser(id: number): Promise<User> {
return this.http.get(this.postUrl+id)
.toPromise()
.then(response => response.json() as User)
.catch(this.handleError);
};
而且我得到錯誤Uncaught (in promise): Error: Error in ./UserPageComponent class UserPageComponent - inline template:1:7 caused by: Cannot read property 'id' of undefined
它看起來就好像該服務沒有發送承諾,儘管它應該。 如何解決這個問題?