如何解决此错误,无法读取未定义的属性“ attribut_id”

时间:2018-09-05 06:25:35

标签: angular

在我加载页面时出现这样的错误:

  

ERROR TypeError:无法读取未定义的属性'attribut_id'

     

评估时(values.component.ts:132)

     

在Array.filter()在   SafeSubscriber.eval [作为_next](values.component.ts:132)

     在

  SafeSubscriber .__ tryOrUnsub(Subscriber.js:243)

     

在SafeSubscriber.next   (Subscriber.js:190)

     

在Subscriber._next(Subscriber.js:131)    在Subscriber.next(Subscriber.js:95)

     

在MapSubscriber._next(map.js:85)   在MapSubscriber.Subscriber.next(Subscriber.js:95)

     

在RefCountSubscriber.Subscriber._next(Subscriber.js:131)

但是错误并不总是并且不时出现。当不存在错误时,数据将完全显示,如果出现错误,则将不会显示数据。

  id: number;
  routeId: any;
  returnUrl: string;
  sprTypeEvents: Array<SprTypeEvent>;
  eventAttributes: Array<EventAttribute>;

  filteredEventAttributes =[];
  _sprTypeEvent: SprTypeEvent;

  public errorMsg;

  constructor(
    public authService: AuthService, 
    private servSprTypeEvent: SprTypeEventService,
    private servEventAttribute: EventAttributeService,
    private router: Router,
    private route: ActivatedRoute
  ) {
    this.sprTypeEvents = new Array<SprTypeEvent>();
  }

  @Input() sprTypeEvent: SprTypeEvent;

  @Input('typeEvent') set typeEvent (value: SprTypeEvent) {
    this._sprTypeEvent = value;
    if(this._sprTypeEvent) {
        this.loadEventAttributes();  
    }
}

  ngOnInit() {
    this.returnUrl = this.route.snapshot.queryParams['returnUrl'] || '/layout/events';
    this.routeId = this.route.params.subscribe(
      params => {
        this.id = +params['id'];
      }
    )
    let sprTypeEventRequest = this.route.params.flatMap(
      (params: Params) => this.servSprTypeEvent.getSprTypeEvent(+params['id'])
    );

    sprTypeEventRequest.subscribe(
      response => this.sprTypeEvent = response.json(),  
      error => this.errorMsg = error
    );

  }

  private loadEventAttributes() {
    this.servEventAttribute.getEventAttributes().subscribe(
      eventAttribute => {
        this.eventAttributes = eventAttribute;
        this.filteredEventAttributes = this.eventAttributes.filter(
          (eventAttribute) => eventAttribute.spr_typeevents_id == this._sprTypeEvent.typeevent_id
        );
      }
    );
  }
}

如何解决?

2 个答案:

答案 0 :(得分:0)

得到异常的原因是因为在ngOnInit方法时输入尚未填充。

只要输入attribute发生更改,就可以使用getter / setter来“通知”:

_attribute: Attribute

@Input('attribute')
set attribute (value: Attribute) {
    this._attribute = value;
    if(this._attribute) {
        this.loadValues();  
    }
}

当然,在您的loadValues方法中,您应该使用this._attribute

答案 1 :(得分:0)

如果未在组件中设置属性值,则可能会发生错误,为避免该错误,您可以像这样实例化属性值

@Input() attribute=new Attribute();

但是您需要进行设置以确保设置了属性值,以便可以显示所有数据