Generaldeep
Generaldeep

Reputation: 445

Angular 6, RxJS return undefined object

my map/filter function aren't returning an object that I am recieving from my in-memory-service.

this.myService.getEventMedia().subscribe(
  (response) => {
    return response.map((res) => {
      this.returnObj = res.dataObj.filter((data) => {
       if(data.id === id) {
         console.log('event is ', data)
         return data;
       }

      })
    })
  }
);

after this response and/or ngAfterViewInit() returnObj is console logging undefinded. My data from the filter function has value in it and i can console log data.id

my model looks like below

export interface Model {
  id: number;
  name: string;
  data: Data[];
}

Upvotes: 0

Views: 1458

Answers (2)

rhavelka
rhavelka

Reputation: 2386

Maybe change your service subscription to this?

this.myService.getEventMedia().subscribe(
  (response) => {
    this.returnObject = response.map((res) => {
      return res.dataObj.filter((data) => {
       if(data.id === id) {
         console.log('event is ', data)
         return data;
       }
      })
    })
  }
);

This way your return object is getting set to the map. Right now returning your map isn't doing anything for you.

Upvotes: 1

Jota.Toledo
Jota.Toledo

Reputation: 28434

You should not return values from the callback methods passed to subscribe, as they are all void in the method signature.

If what you want to do is transform the response of your service in some manner, and then assign the transformed value to the returnObj class member, then you should do something like the following:

this.myService.getEventMedia()
  .pipe(
      map(response => this.transformResponse(response))
   )
  .subscribe(mappedResponse => this.returnObj = mappedResponse);

private transformResponse(response:Object): Object {
   // your transformation logic goes here
}

Upvotes: 0

Related Questions