0

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[];
}
7
  • 1
    You shouldn't return something from a subscribe block. What are you trying to accomplish? Commented Jun 12, 2018 at 16:29
  • I want to assign the matching data to returnObj, i'm still new to rxjs so still learning Commented Jun 12, 2018 at 16:31
  • @Generaldeep can you show the json for response?
    – CozyAzure
    Commented Jun 12, 2018 at 16:53
  • @CozyAzure, the response is an object with 2 arrays that contains multiple objects. I can't share the json response due to privacy issues. Commented Jun 12, 2018 at 16:56
  • filter inside map is not a good idea, though
    – Kstro21
    Commented Jun 12, 2018 at 17:17

2 Answers 2

1

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.

0

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
}

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.