开发者问题收集

未定义的未定义的属性(在承诺中):无法读取未定义

2016-09-15
61333

组件从服务中获取带有参数的用户

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

    };

我收到错误 未捕获(在承诺中):错误:./UserPageComponent 类 UserPageComponent 中的错误 - 内联模板:1:7 导致:无法读取未定义的属性“id”

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

1个回答

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

@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>

它应该可以工作

obenjiro
2016-09-15