简体   繁体   中英

Angular TypeError cannot set property 'Data' of undefined

In my code, I am calling this operation in ngOnInit to be able to see previously edited data when the page reopens. StickerData is a property of IStickerData which is an interface. I keep getting

ERROR TypeError: Cannot set property 'StickerData' of undefined
at SafeSubscriber._next (sticker-preview.component.ts:54)
    at SafeSubscriber.__tryOrUnsub (Subscriber.js:183)
    at SafeSubscriber.next (Subscriber.js:122)
    at Subscriber._next (Subscriber.js:72)
    at Subscriber.next (Subscriber.js:49)
    at FinallySubscriber._next (Subscriber.js:72)
    at FinallySubscriber.next (Subscriber.js:49)
    at CatchSubscriber._next (Subscriber.js:72)
    at CatchSubscriber.next (Subscriber.js:49)
    at MapSubscriber._next (map.js:35)

error on subscribe((response: any) => this._stickerData.StickerData = response); when I open the page. What am I missing here?

TS:

private _stickerData: IStickerData;
Filter: IFilter;

@Input()
  set StickerData(prm: IStickerData) {
      if (this._stickerData != prm) {
          this._stickerData = prm;
      }
  }
  get StickerData(): IStickerData {
      return this._stickerData;
  }

 ngOnInit() {
    this._productionService.getStickerDataList(this.Filter)
    .subscribe((response: any) => this._stickerData.StickerData = response);
    
  }

service TS:

getStickerDataList(data: IFilter): Observable<IStickerData[]> {
        return this._http.post("Production/GetStickerDataList", data);
    }

You need to initialize the variable before accessing it's properties.

private _stickerData: IStickerData = Object.create(null);

And it looks like at the moment the variable this.Filter is also left undefined before sending it to the service.

You're doing this._stickerData.StickerData = [...] but this._stickerData is not initialized, thus it has the value undefined .

You may want to add a default value with:

private _stickerData: IStickerData = {};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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