我想知道是否有人可以向我解釋這個錯誤,因為我對 angular、typescript 和 rxjs 比較陌生。
我嘗試做的是以getHeroes()一種格式映射我獲得的服務器回應,以便我的組件可以輕松使用它。
這是我的getHeroes()作業方法:
getHeroes(): Observable<Hero[]> {
const heroes = this.http.get<any>(this.heroesUrl)
.pipe(
map((res: EmbeddedResponse) => res._embedded.heroes),
tap(data => this.log('HeroService: fetched Heroes'),
catchError(this.handleError<Hero[]>('getHeroes', []))
))
return heroes
}
注意中的any型別引數this.http.get<any>()
我想更具體地使用型別引數getHeroes():
getHeroes(): Observable<Hero[]> {
const heroes = this.http.get<Hero[]>(this.heroesUrl)
.pipe(
map((res: EmbeddedResponse) => res._embedded.heroes),
tap(data => this.log('HeroService: fetched Heroes'),
catchError(this.handleError<Hero[]>('getHeroes', []))
))
return heroes
}
注意Hero[]型別引數this.http.get<Hero[]>()
但是getHeroes()從any -> Hero[]更改型別引數會解決此錯誤:
error TS2345: Argument of type 'OperatorFunction<EmbeddedResponse, Hero[]>' is not assignable to parameter of type 'OperatorFunction<Hero[], Hero[]>'.
Property '_embedded' is missing in type 'Hero[]' but required in type 'EmbeddedResponse'.
EmbeddedResponse 介面如下所示:
interface EmbeddedResponse {
_embedded: {
heroes: Hero[]
}
}
來自服務器的回應如下所示:
{
"_embedded" : {
"heroes" : [ {
"id" : 1,
"name" : "Dicke Berta",
"_links" : {
"self" : {
"href" : "http://localhost:8080/heroes/1"
},
"hero" : {
"href" : "http://localhost:8080/heroes/1"
}
}
}, {
"id" : 5,
"name" : "Cobra-Car",
"_links" : {
"self" : {
"href" : "http://localhost:8080/heroes/5"
},
"hero" : {
"href" : "http://localhost:8080/heroes/5"
}
}
} ]
},
"_links" : {
"self" : {
"href" : "http://localhost:8080/heroes"
},
"profile" : {
"href" : "http://localhost:8080/profile/heroes"
},
"search" : {
"href" : "http://localhost:8080/heroes/search"
}
}
}
uj5u.com熱心網友回復:
您在 get 中定義的回傳型別僅分配給 get 函式本身,而不是整個鏈。您定義了 get 回傳型別 Hero[],但在地圖中您希望它是 EmbeddedResponse 型別。而是定義 get 以回傳 EmbeddedResponse:
this.http.get<EmbeddedResponse>(this.heroesUrl)
然后你甚至不需要在地圖中定義“res”的型別,因為它已經定義了(盡管你也可以保留它以提高可讀性):
map((res) => res._embedded.heroes)
您的鏈的回傳型別由最后一個元素回傳的內容定義,在您的案例地圖中。res._embedded.heroes 是 Hero[] 型別,因此你的 const 英雄將是 Observable<Hero[]> 型別。
最后,在 tap 和 catchError 中,您可能將括號設定錯了。catchError 不應該是 tap 的一部分,而是應該在它之后鏈接:
tap(data => this.log('HeroService: fetched Heroes')),
catchError(this.handleError('getHeroes', []))
);
uj5u.com熱心網友回復:
您的catchError操作員應該在管道內而不是在管道內tap
pipe(
map((res: EmbeddedResponse) => res._embedded.heroes),
tap(data => this.log('HeroService: fetched Heroes')),
catchError(this.handleError<Hero[]>('getHeroes', []))
))
演示
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/317149.html
上一篇:打字稿-強制值成為介面的屬性
