Home > Software design >  for map operator in Rxjs
for map operator in Rxjs

Time:06-11

Recently I just learned a little about rxjs and Angular. And when I tried to write an api to access some web service.

I defined this type :

    export type Banner = {
           targetId: number;
           url: string;
           imageUrl: string;
    }

and the service part is :

export class HomeService {

  constructor(private http: HttpClient,
              @Inject(API_CONFIG) private uri: string) { }

  getBanners(): Observable<Banner[]> {
    return this.http.get(this.uri   'banner')
      .pipe(map((res: { banners: Banner[] }) => res.banners));
  }
}

and tge receiving data is like this

{
"banners": [
{
"imageUrl": "http://p1.music.126.net/64Nc0mcg6Sjq56TzCLDpQA==/109951167536067432.jpg",
"targetId": 0,
"adid": null,
"targetType": 3000,
"titleColor": "blue",
"url": "https://music.163.com/m/at/62a19bee9c36d0102fa275f4",
"exclusive": false,
"monitorImpress": null,
"monitorClick": null,
"monitorType": null,
"monitorImpressList": null,
"monitorClickList": null,
"monitorBlackList": null,
"extMonitor": null,
"extMonitorInfo": null,
"adSource": null,
"adLocation": null,
"adDispatchJson": null,
"encodeId": "0",
"program": null,
"event": null,
"video": null,
"song": null,
"scm": "1.music-homepage.homepage_banner_force.banner.4747964.341110454.null"
},
{
"imageUrl": "http://p1.music.126.net/MLX8OCPeIzlyxGGaHz3IbQ==/109951167532698136.jpg",
"targetId": 1954420092,
"adid": null,
"targetType": 1,
"titleColor": "red",
"url": null,
"exclusive": false,
"monitorImpress": null,
"monitorClick": null,
"monitorType": null,
"monitorImpressList": null,
"monitorClickList": null,
"monitorBlackList": null,
"extMonitor": null,
"extMonitorInfo": null,
"adSource": null,
"adLocation": null,
"adDispatchJson": null,
"encodeId": "1954420092",
"program": null,
"event": null,
"video": null,
"song": null,
"scm": "1.music-homepage.homepage_banner_force.banner.4725970.341201780.null"
}
}

When I tried to compile the code, compiler told me sth like this:

Error: src/app/service/home.service.ts:18:13 - error TS2345: Argument of type 'OperatorFunction<{ banners: Banner[]; }, Banner[]>' is not assignable to parameter of type 'OperatorFunction<Object, Banner[]>'. The 'Object' type is assignable to very few other types. Did you mean to use the 'any' type instead? Property 'banners' is missing in type 'Object' but required in type '{ banners: Banner[]; }'.

Typescript version: 4.5.2

Angular version: 13.1.0

CodePudding user response:

Try to specify the response type of the HTTP client as well:

return this.http.get<{ banners: Banner[] }>(this.uri   'banner')
...
  • Related