Wei*_*eit 13 javascript angular
组件使用params服务用户
@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})
});
}
Run Code Online (Sandbox Code Playgroud)
服务:
@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);
};
Run Code Online (Sandbox Code Playgroud)
我得到错误 Uncaught (in promise): Error: Error in ./UserPageComponent class UserPageComponent - inline template:1:7 caused by: Cannot read property 'id' of undefined
它看起来好像服务没有发送承诺,尽管它应该.如何解决这个问题?
obe*_*iro 21
看起来您的组件没有用户的默认值,因此在组件渲染时尝试添加默认值时未定义
@Component({
selector: 'users',
providers: [UserService],
template: `
<p>{{user.id}}</p>
`
})
export class UserPageComponent implements OnInit {
user = {} // default value for user
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})
});
}
Run Code Online (Sandbox Code Playgroud)
实际上,最好在这里添加一些条件逻辑
<p *ngIf="user">{{user.id}}</p>
Run Code Online (Sandbox Code Playgroud)
它应该工作
| 归档时间: |
|
| 查看次数: |
37804 次 |
| 最近记录: |