vashlor
vashlor

Reputation: 53

Angular 7 Transform Observable response to a new observable object

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

Upvotes: 0

Views: 2346

Answers (1)

Razvan Fulea
Razvan Fulea

Reputation: 447

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 */ }
)

Upvotes: 1

Related Questions