【问题标题】:Angular2 object cannot set property of undefinedAngular2 对象无法设置未定义的属性
【发布时间】:2019-09-26 21:17:25
【问题描述】:

所以我在 Angular2 中有这个小应用程序,我正在尝试定义一个对象。这是主要组件。

export class ContactComponent  {
    person: {
    firstname: string;
    lastname: string;
}
constructor(private PeopleService: PeopleService){
}

ngOnInit(){

this.PeopleService.fetchData().subscribe(
    data=> {
        this.person.firstname=data.results[0].name.first;
        console.log(this.person.firstname);
    });
  }
}

然后在控制台日志中我得到:

无法设置未定义的属性“名字”

我想不通。谢谢。

【问题讨论】:

    标签: angular object undefined


    【解决方案1】:

    您只是在这里定义person 的类型(冒号代表类型注释,例如:propertyName:Type):

    person: {
        firstname: string;
        lastname: string;
    }
    

    您在这里所做的是告诉编译器person 是一个具有两个字符串属性firstnamelastname 的对象文字。它定义了可以存储在该属性中的内容,而不是它包含的内容。

    你应该先赋值,否则会是undefined

    interface Person {
        firstname ? : string; // the "?" makes the property optional, 
        lastname ? : string; //  so you can start with an empty object
    }
    export class ContactComponent {
    
        person: Person = {}; // initializing with an empty object
    
        constructor(private PeopleService: PeopleService) {}
    
        ngOnInit() {
    
            this.PeopleService.fetchData().subscribe(
                data => {
                    this.person.firstname = data.results[0].name.first;
                    console.log(this.person.firstname);
                });
        }
    }
    

    【讨论】:

    • 你能看看这个gyazo.com/2ef08d144e87fc28f83fbfe83d974bf3,我从http请求中得到50个结果,但是[1]的第二个console.log不起作用。知道为什么吗?这是同样的错误'无法设置...'
    • 当然我不会手动创建每个条目,我只是想检查它是否有效,我也尝试了 for
    • this.person=data.results.map(()=>{firstname:item.name.first,lastname:item.name.last}) 但我的意思是,如果你有这样的问题,你可能不应该从 angular 2 开始,也许更简单一些,因为初学者 angular 2 的学习曲线很陡。
    • 我做到了,谢谢!那是因为数组没有隐式长度,对吧?
    • 那是因为第二个条目 (array[1]) 还不存在。它是未定义的,不是人,你不能在未定义上设置属性...
    【解决方案2】:

    创建一个类并在组件中继承。例如看下面的代码

           export class Person{
    
                firstname: string;
                lastname: string;
            }
            export class ContactComponent  {
            person=Person[];
            constructor(private PeopleService: PeopleService){
            }
    
            ngOnInit(){
    
            this.PeopleService.fetchData().subscribe(
                data=> {
                    this.person.firstname=data.results[0].name.first;
                    console.log(this.person.firstname);
                });
              }
            }
    

    【讨论】:

      【解决方案3】:

      首先在onInit()上声明一个person类型的对象。

      person p=new person();
      

      【讨论】:

        【解决方案4】:
        1. 首先在组件类中创建一个对象。例如:

          employee=new Employee();
          
        2. 然后引用这个employee对象

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2017-06-06
          • 2020-03-06
          • 2021-11-27
          • 1970-01-01
          • 2022-10-30
          • 2023-02-10
          • 1970-01-01
          相关资源
          最近更新 更多