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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39507581/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 22:38:32  来源:igfitidea点击:

Uncaught (in promise): Error: Cannot read property of undefined

javascriptangular

提问by Weit

Component take user from service with 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})
        });
    }

Service :

服务 :

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

    };

And I get Error Uncaught (in promise): Error: Error in ./UserPageComponent class UserPageComponent - inline template:1:7 caused by: Cannot read property 'id' of undefined

我得到错误 Uncaught (in promise): Error: Error in ./UserPageComponent class UserPageComponent - inline template:1:7 caused by: Cannot read property 'id' of undefined

It looks as if the service does not send the promise, although it should. How to solve this proble?

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

回答by obenjiro

It looks like your component doesn't have default value for user, so it is undefined when component rendered try adding default value

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

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

actually it will be better to add some conditional logic here then

实际上最好在这里添加一些条件逻辑然后

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

it should work

它应该工作