首页 > 解决方案 > enforce order using pipe with mergeMap in Angular

问题描述

I'm a newbie to Angular and stumbling with this. getIds returns an array of Ids and then we create an Observable(getNames) for each of these Ids.

interface Name{
    "Id": string;
    "": string;
    "cve_link": string;
    "cve_description": string;
    "cve_applications": string;
    "cve_hosts": string;
    }
export interface Vulns extends Array<Vuln>{}

getIds(): void {
 this.cvetservice
     .getIds().pipe(
     mergeMap(names => this.getNames(this.ids)),
     mergeMap(names => names),
     toArray()
     )
}

getNames(data: Ids):Observable<any[]> {
 return this.http
    .post(url,data)
    .pipe(map(({ Results }: any) => Results[0].results.map(item => ({Id: item.Id, Name: item.Name }))));
    }

The line 133 mergeMap(names => names) fails to compile (error below).

ERROR in src/app/mcomponent.ts(133,19): error TS2345: Argument of type '(names: Name) => Name' is not assignable to parameter of type '(value: Name, index: number) => ObservableInput<{}>'.
Type 'Name' is not assignable to type 'ObservableInput<{}>'.
Type 'Name' is not assignable to type 'Iterable<{}>'.
Property '[Symbol.iterator]' is missing in type 'Name'.
src/app/mcomponent.ts(138,28): error TS2355: A function whose declared type is neither 'void' nor 'any' must return a value.

Can someone help clarify what I'm doing wrong here?

标签: angularhttp

解决方案


乍一看您的代码。这是问题

getIds(): Observable<any[]> {
 return this.cvetservice
     .getIds().pipe(
     mergeMap(names => this.getNames(this.ids)),
     mergeMap(names => names),
     toArray()
     )
}

getNames(data: Ids):Observable<any[]> {
 return this.http
    .post(url,data)
    .pipe(map((Results : any) => Results[0].results.map(item => ({Id: item.Id, Name: item.Name }))));
    }

提供 JSON 响应,stackblitz 将增加更多价值。


推荐阅读