Angular 如何转换http.get()响应,以便组件能够直接使用结果

Angular 如何转换http.get()响应,以便组件能够直接使用结果,angular,rxjs,Angular,Rxjs,我想转换数据获取的结果,以便组件可以使用它 响应作为对象返回 我需要投影对象的属性关键字,它包含一个对象数组: 给我一个字符串数组: /['foo','bar'] 我知道我需要pipe()和map()来实现这一点。但我的解决方案是生成类型错误 服务方式: public getKeywords(): Observable<Array<string>> { return this.http.get<Observable<GetKeywordsResp

我想转换数据获取的结果,以便组件可以使用它

  • 响应作为对象返回

  • 我需要投影对象的属性
    关键字
    ,它包含一个对象数组:

给我一个字符串数组:
/['foo','bar']

我知道我需要
pipe()
map()
来实现这一点。但我的解决方案是生成类型错误

服务方式:

public getKeywords(): Observable<Array<string>>  {
    return this.http.get<Observable<GetKeywordsResponse>>(...url).pipe(
      map((res: GetKeywordsResponse): Array<KeywordObj> => res.keywords),
      map((res: KeywordObj): Array<string> => res.keyword )
  }
publicGetKeywords():可观察{
返回此.http.get(…url).pipe(
map((res:GetKeywordsResponse):数组=>res.keywords),
map((res:KeywordObj):数组=>res.keyword)
}
我希望该方法不会出现任何问题。但是我遇到了两个错误:

1. Argument of type 'OperatorFunction<GetKeywordsResponse, KeywordObj[]>' is not assignable to parameter of type 'OperatorFunction<Observable<GetKeywordsResponse>, KeywordObj[]>'.
 Type 'GetKeywordsResponse' is missing the following properties from type 'Observable<GetKeywordsResponse>': _isScalar, source, operator, lift, and 6 more.

2. Type 'string' is not assignable to type 'string[]'.
1.“OperatorFunction”类型的参数不能分配给“OperatorFunction”类型的参数。
类型“GetKeywordsResponse”缺少类型“Observable”中的以下属性:\ isScalar、source、operator、lift等6个。
2.类型“string”不可分配给类型“string[]”。
如何修复getKeywords()?

public getKeywords():可观察{
返回this.http.get(`${this.uri}/businesss/${this.businessId}/keywords`).pipe(
map((res:GetKeywordsResponse):数组=>res.keywords),
map((arr:Array):string[]=>arr.map((obj:KeywordObj):string=>obj.keyword)))
}
  • 第二个映射的输入返回了一个对象数组。我错误地认为它是对象数组中的一个项

确保您是从
rxjs/operators
导入
map
,而不是从
rxjs
导入的。此外,当前您会得到一个
可观察的
,而不是
可观察的
,因为
关键字
是单个字符串。请尝试在映射之后添加
toArray()
操作符。
public getKeywords(): Observable<Array<string>>  {
    return this.http.get<Observable<GetKeywordsResponse>>(...url).pipe(
      map((res: GetKeywordsResponse): Array<KeywordObj> => res.keywords),
      map((res: KeywordObj): Array<string> => res.keyword )
  }
1. Argument of type 'OperatorFunction<GetKeywordsResponse, KeywordObj[]>' is not assignable to parameter of type 'OperatorFunction<Observable<GetKeywordsResponse>, KeywordObj[]>'.
 Type 'GetKeywordsResponse' is missing the following properties from type 'Observable<GetKeywordsResponse>': _isScalar, source, operator, lift, and 6 more.

2. Type 'string' is not assignable to type 'string[]'.
public getKeywords(): Observable<string[]>  {
   return this.http.get(`${this.uri}/businesses/${this.businessId}/keywords`).pipe(
     map((res: GetKeywordsResponse): Array<KeywordObj> => res.keywords),
     map((arr: Array<KeywordObj>): string[] => arr.map((obj: KeywordObj): string => obj.keyword)))
 }