0
votes

I have an api which responses like this and I am using rxjs observables

[{
  "error": "error_1",
  "types": [
     {
       "type": "new_type"
     },
     {
       "type": "old_type"
     }
  ],
  "date": "2019-08-29"
}]

I need to transform it into a new json format so i can get the response format i wanted.

I have tried pipe(map()) but i get error that Type 'Observable<void>' is not assignable to type 'Observable<Error[]>'

My Model

export interface Data {
    error: string,
    types: Types[],
    date: string
}

interface Types {
    type: string
}

My Service.ts

getError(): Observable<Data[]> {
    return this.http.get<Data[]>(url);
  }

This is what i tried so far and i deleted the code which produces error My Component.ts

getUserErrors(user): Observable<Data[]> {
    return this.getData.getError()
      .pipe(map((x) => x.filter(one => one.error !== null)))
}

Here is the observable output i need

[{
  "new_error": "error_1",
  "type_1": "new_type",
  "date": "2019-08-29"
}]

Thank you for those who will help

1
I do not see anything in your code that should produce the error. I suggest you put together a Minimal Reproducible Example, preferably using StackBlitz - dmcgrandle
is that supposed to be getError(): Observable<Data[]> { - Pradeep
@Pradeep yes. just a typo. I will edit it - vashlor
Post the actual code, the actual error, and the precise line to which the error refers to. The error is about an Observable<Error[]>, and all the code you posted has nothing to do with Error. - JB Nizet

1 Answers

0
votes

As far as I understand, you need to filter out the responses with null errors, then map the remaining elements to the new format, and return that as another Observable. You can use flatMap in order to chain multiple Observables together:

getUserErrors(user): Observable<Data[]> {
    return this.getError()
        .flatMap(result => {
            result = result.filter(elem => elem.error !== null)
                .map(elem => ({
                    new_error: elem.error,
                    type_1: elem.types[0].type, // since you want the first out of the two
                    date: elem.date
                }));
            return Observable.of(result);
        })
}

Later on when you call this:

this.getUserErrors(user).subscribe(
    result => { console.log(result); }
    error => { console.log(error); /* Do some proper error handling */ }
)