简体   繁体   English

Angular2不能在模板以外的任何地方访问变量

[英]Angular2 cant acces variable anywhere but in template

I have problem with accesing array inside component in place other than template. 我无法在模板以外的地方访问组件内部的数组。 I have students: Student[]; 我有students: Student[]; which is then filled by data from json in 然后由json中的数据填充

getStudents() {
    this.studentService.getStudents()
        .subscribe(
        students => this.students = students,
        error => this.errorMessage = <any>error );
}

I can display this data in template via 我可以通过以下方式在模板中显示此数据

<tr *ngFor="let student of students">
    <td>{{ student.id }}</td>
    <td>{{ student.firstName }}</td>
    <td>{{ student.lastName }}</td>
</tr>

but, if I try to do something like 但是,如果我尝试做类似的事情

this.students.forEach(
            s => {
                console.log(s.getFirstName());
            });

i get Cannot read property 'forEach' of undefined 我得到Cannot read property 'forEach' of undefined

If I however initialize array as students: Student[] = new Array; 但是如果我将数组初始化为students: Student[] = new Array; i dont get error, but array stays empty. 我没有收到错误,但数组保持为空。 Method getStudents() is called from ngOnInit(). 从ngOnInit()调用方法getStudents()。 What am I missing? 我想念什么?

EDIT 编辑

Thanks everyone who tried to help. 感谢所有尝试提供帮助的人。 However none of the solutions worked for me. 但是,没有一种解决方案对我有用。 getStudents() is first method I call in ngOnInit. getStudents()是我在ngOnInit中调用的第一个方法。 I just dont understand, why does listing it in template work, but for rest of component array appears to be empty. 我只是不明白,为什么要在模板中列出它,但是对于其余的组件数组似乎是空的。 If I add values to array later, via students.push, they are only values I can access. 如果我稍后通过students.push将值添加到数组,则它们只是我可以访问的值。

try to use elvis operator white fetching data from service like this 尝试使用elvis operator白色从这样的服务中获取数据

<tr *ngFor="let student of students">
    <td>{{ student?.id }}</td>
    <td>{{ student?.firstName }}</td>
    <td>{{ student?.lastName }}</td>
</tr>

No need to use forEach 无需使用forEach

sometimes template loads before getting data from the service so in this case elvis operator will prevent from throwing error 有时会在从服务获取数据之前加载template ,因此在这种情况下,elvis操作员将防止抛出错误

When you declared students objects like 当您声明学生对象时

students: Student[] 

please take a deep look into it. 请深入研究它。 you are declaring variable[students] of array of student not initialize it. 您正在声明学生数组的变量[学生]未初始化它。 that means your students is null. 这意味着您的学生为空。 So when you are using forEach method on null you you are getting error like 'Cannot read property 'forEach' of undefined' 因此,当您对null使用forEach方法时,会收到类似“无法读取未定义的属性'forEach'的错误”

you can do like 你可以喜欢

students: Student[] = [];

then use 'forEach' hope. 然后使用“ forEach”的希望。 you will not get any error. 您不会得到任何错误。

The issue is combination of the the students array not being initialized when the forEach is run and with how Angular2's life-cycle hooks work. 问题是在运行forEach时未初始化students数组以及Angular2的生命周期挂钩如何工作的组合。

ngOnInit is the second method that is called when a component is created, after an initial call to ngOnChanges . ngOnInit是在初始调用ngOnChanges之后创建组件时调用的第二种方法。 If the call to this.studentService.getStudents() hasn't returned by the time the the forEach is called then the error will occur because the students array has not been initialized yet. 如果在调用forEach时尚未返回对this.studentService.getStudents()的调用,则将发生错误,因为尚未初始化students数组。

The ngOnInit method only gets called once for each component so the reason you aren't seeing any data printed to the console is that when the loop is called it has not received data from the service yet. ngOnInit方法对于每个组件仅被调用一次,因此您看不到打印到控制台的任何数据的原因是,在调用循环时,它尚未从服务接收数据。

I am not sure what your use case is but what I like to do when I need to perform actions on data returned from a service is to create a function that I call from the service callback: 我不确定您的用例是什么,但是当我需要对从服务返回的数据执行操作时想要做的事情是创建一个从服务回调中调用的函数:

getStudents() {
    this.studentService.getStudents()
        .subscribe(
            students => {
                this.students = students;
                this.printStudents();
            },
            error => this.errorMessage = <any>error );
}

printStudents() {
    this.students.forEach(
        s => {
            console.log(s.getFirstName());
        });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM