简体   繁体   中英

How to use map in rxjs/operator

API call returns data as list of IAthing and I would like to map to List of Select2OptionData

[
    {
        "prop1": 'vbn',
        "prop2": 'abc'
    },
    {
        "prop1": 'fgh',
        "prop2": 'tyyty'
    }
]

In this method from service file I get this error:

[ts] Type 'Observable<Select2OptionData>' is not assignable to type 'Observable<Select2OptionData[]>'

 getMethod(
    term: string = '',
    page: number = 0
  ): Observable<Select2OptionData[]> {
    return this.http
      .get(`/api/something/foobar?q=${term}&page=${page}`)
      .pipe(
        map((data: IAthing) => {
          return <Select2OptionData>{ id: data.prop1.toString(),
             text: data.prop2 };
        }),
        catchError(this.handleError)
      );
  }

Select2OptionData interface

export interface Select2OptionData {
    id: string;
    text: string;
    disabled?: boolean;
    children?: Array<Select2OptionData>;
    additional?: any;
}

export interface IAthing {
  prop1: string;
  prop2: string;
}

What am I doing wrong here

This is a signature error.

You expect

Observable<Select2OptionData[]>

Which is an array of objects, but you return

<Select2OptionData>{ id: data.prop1.toString(),
         text: data.prop2 }

Which is an object. Either change your map function, or your signature.

To return an array :

.pipe(
  map(response => response.map(item => ({ id: item.prop1, text: item.prop2 })))
)

You can write pipe function as follows:

getMethod(
term: string = '',
page: number = 0
): Observable<Select2OptionData[]> {
return this.http.get(`/api/something/foobar?q=${term}&page=${page}`)
  .pipe(
  .map(this.extractData)
  .catch(this.handleErrorObservable));

}

Handle error and data here

 // if get successful response extract response
 private extractData(res: Response) {
 if (res.status === 200) {
  const body = res.json();
  return body;
  } else {
  return {};
  }
}

private handleErrorObservable(error: any) {
   // 401 - unAuthorized
   if (error) {
     return Observable.throw(new Error(error.status));
   }
   else {
      return Observable.throw(new Error(error.status));
    }

  }

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