简体   繁体   English

在ngOnInit上未定义Angular 2属性

[英]Angular 2 attribute is undefined on ngOnInit

I'm new to web developing with AngularJs 2 and I don't have experience with AngularJs 1 too . 我是使用AngularJs 2进行Web开发的新手, 我也没有使用AngularJs 1的经验 So, I'm sorry if I'm asking something stupid. 所以,如果我问一些愚蠢的话,我很抱歉。 I'm stuck on a problem and I googled it but I couldn't find any solutions for it. 我遇到了问题,我用Google搜索,但我找不到任何解决方案。 :/ :/

The problem is: 问题是:

I'm trying to use in a function called at the end of ngOnInit an attribute of an object that I initialize on ngOnInit , but this object is still undefined , so I get the following exception: 我正在尝试在ngOnInit结束时调用的函数中使用我在ngOnInit上初始化的对象的属性,但是这个对象仍未定义 ,因此我得到以下异常:

Error: Uncaught (in p**strong text**romise): TypeError: Cannot read property 'secretariatId' of undefined

Here is my component: 这是我的组件:

import {Component, OnInit, AfterViewChecked} from '@angular/core';
import { ActivatedRoute, Router, Params } from '@angular/router';

import {StudentService} from './services/student.service';
import {Student} from './services/student';

import {SecretariatService} from './services/secretariat.service';

import {DisciplineService} from './services/discipline.service';
import {Discipline} from './services/discipline';


@Component({
  selector: 'fountain-enrollstudent',
  template: require('./templates/enrollstudent.component.html')
})
export class EnrollStudentComponent implements OnInit, AfterViewChecked {
  public text: string;
  selectedDiscipline: Discipline;
  disciplines: Discipline[];
  student: Student;

  constructor(
    private disciplineService: DisciplineService,
    private studentService: StudentService,
    private secretariatService: SecretariatService,
    private router: Router,
    private route: ActivatedRoute
  ) {
    this.text = 'My brand new component!';
  }

   ngOnInit(): void {
    this.route.params.forEach((params: Params) => {
      console.log(params);
      let id = +params['id'];
      this.getStudent(id);
      console.log(id);
      console.log(this.student);
      this.getDisciplines(this.student.secretariatId);
     });

     console.log(this.student);

   }

  // Understand the best moment to call it. Ps.: It doesn't work on ngOnInit
  getDisciplines(secretariatId: number): void {
     this.disciplineService.getDisciplinesBy(secretariatId)
      .then(disciplines => this.disciplines = disciplines);
  }

  getStudent(id: number): void {
     this.studentService.getStudent(id)
       .then(student => this.student = student);
  }

  onSelect(discipline: Discipline): void {
     this.selectedDiscipline = discipline;
  }
}

Here is my template: 这是我的模板:

<div class="text-center">
  <h4>Disciplines:</h4>
  <ul class="list-unstyled">
    <li *ngFor="let discipline of disciplines" (click)="onSelect(discipline)" [class.selected]="discipline === selectedDiscipline">
      <h4>
        <a>{{discipline?.name}}</a>
      </h4>
    </li>
  </ul>
</div>

Here is the DisciplineService: 这是DisciplineService:

 import { Injectable } from '@angular/core';

 import { Discipline } from './discipline';
 import { DISCIPLINES } from './mock-disciplines';

@Injectable()
export class DisciplineService {

  getDisciplines(): Promise<Discipline[]> {
    return Promise.resolve(DISCIPLINES);
  }

  getDisciplinesBy(secretariatId: number): Promise<Discipline[]> {
     return this.getDisciplines()
      .then(disciplines => disciplines.filter(discipline => discipline.secretariatId === secretariatId));
  }
}

I was looking for another Lifecycle Hooks to call the function getDisciplines(id: number), but I tried them all and I had no good results. 我正在寻找另一个生命周期钩子来调用函数getDisciplines(id:number),但我尝试了所有这些并且我没有取得好成绩。 :/ :/

Thanks in advance! 提前致谢!

You need to chain async calls: 你需要链接异步调用:

ngOnInit(): void {
  this.route.params.forEach((params: Params) => {
    console.log(params);
    let id = +params['id'];

    // vvvvvvvv use `.then(...)`
    this.getStudent(id).then(student => {  
      console.log(id);
        console.log(this.student);
        this.getDisciplines(this.student.secretariatId);
    });
  }
}

getStudent(id: number): void {
   // vvvvvvvv return the promise so callers can chain their code
   return this.studentService.getStudent(id)
     .then(student => this.student = student);
}

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

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