未捕获(承诺中):错误:无法读取未定义的属性

2024-04-15

组件使用参数将用户从服务中取出

@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

看起来该服务似乎没有发送承诺,尽管它应该发送。 如何解决这个问题呢?


看起来您的组件没有用户的默认值,因此当组件呈现时尝试添加默认值时它是未定义的

@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})
        });
    }

实际上在这里添加一些条件逻辑会更好

<p *ngIf="user">{{user.id}}</p>

它应该有效

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

未捕获(承诺中):错误:无法读取未定义的属性 的相关文章