我通过在资产文件中声明这一行来和平地从口袋妖怪的api中检索所有内容:
export const configUrl = {
pokemonBaseUrl: 'https://pokeapi.co/api/v2/',
};
并在我的服务中这样调用它:
getPokemons(offset: number): Observable<any> {
return this.httpClient.get(`${configUrl.pokemonBaseUrl}pokemon-species?offset=${offset}&limit=20`)
.pipe(
map((pokemonList: PokemonList) => this.addAdditionalPropertiesToEntity(pokemonList))
);
}
然后在副作用中称呼它:
@Effect()
loadInitialPokemons$: Observable<Action> = this.actions$.pipe(
ofType(MasterDetailActionTypes.StartLoadMasterDetails),
switchMap((action: StartLoadMasterDetails) => this.pokemonService.getPokemons(action.payLoad.offset)),
switchMap(result => of(new EndLoadMasterDetails(result))),
catchError(err => of(new OnError(err.message)))
);
具有以下操作类型:
export class StartLoadMasterDetails implements Action {
readonly type = MasterDetailActionTypes.StartLoadMasterDetails;
readonly payLoad = {
offset: 0
};
}
然后在我的组件内部,我得到如下的初始数据:
ngOnInit() {
this.createStateSubscriptions();
this.createEventScrollSubscription();
this.store.dispatch(new actions.StartLoadMasterDetails());
}
我的html如下:
<div class="master-container">
<div class="wrapper-scroll-y grid-scrollbar">
<div class="tiles-container" *ngIf="(pokemonObservable$|async).pokemonList">
<div class="card" *ngFor="let pokemon of (pokemonObservable$|async).pokemonList.results">
<div (click)= "onPokemonSelected($event, pokemon.id)">
<div class="card-body">
<img src="{{pokemon.spriteUrl}}">
</div>
<div class="card-footer footer">{{pokemon.name}}</div>
</div>
</div>
</div>
</div>
<app-loader-indicator [show]="(pokemonObservable$|async).processingMaster"></app-loader-indicator>
</div>
现在我要做什么,而不是直接从服务器检索此数据,我想将其放入文件中。 我尝试了这个:
export const configUrl = {
pokemonBaseUrl: {
'pokemon-species': {
'results': [
{
'name': 'bulbasaur',
'url': 'https://pokeapi.co/api/v2/pokemon-species/1/'
},
{
'name': 'ivysaur',
'url': 'https://pokeapi.co/api/v2/pokemon-species/2/'
}
]
}
},
};
并将我的http请求更改为:
getPokemons(offset: number): Observable<any> {
return this.httpClient.get(`${configUrl.pokemonBaseUrl["pokemon-species"]}`)
.pipe(
map((pokemonList: PokemonList) => this.addAdditionalPropertiesToEntity(pokemonList))
);
}
当我在控制台上登录configUrl.routeBaseUrl [“ pokemon-species”]时,我在文件中获取了数据,但是一旦运行项目,我就会收到此错误:
答案 0 :(得分:1)
看来,您只是想直接将数据嵌入到应用程序中,而不是从API检索数据。在这种情况下,您的角度服务将不再需要HttpClient
依赖性。
假设configUrl
现在只是具有整个数据集的文档,则可以直接查询该文档,将调用交换到httpClient.get
。
例如,您的getPokemons
方法可能看起来像这样:
getPokemons(offset: number): Observable<any> {
const numberToRetrieve = 5;
const pokemon = configUrl.pokemonBaseUrl["pokemon-species"]["results"];
return of(pokemon.slice(offset, numberToRetrieve));
}
您还需要在 rxjs 导入中添加of
函数。
import {
Observable,
of // Add this
} from 'rxjs';
我不熟悉您之前调用的API,但是我假设它一次只返回了一些结果。我添加了numberToRetrieve
作为占位符,以使您仅能获得下5个神奇宝贝。该数字显然可以是您想要的任何数字,甚至可以是函数的参数。