您好,我是新用户,在单击事件后在按钮中添加了一组新的API网址后,我想刷新组件 这是我的代码。 pokemons.service.ts
export class PokemonsService {
private _url: string = "https://pokeapi.co/api/v2/pokemon";
private _pokemonUrl: string;
constructor(private http : HttpClient) { }
setUrl(value: string){
this._url = value;
}
getUrl(): Observable<IPokemon[]>{
return this.http.get<IPokemon[]>(this._url);
}
setPokemonUrl(value: string){
this._pokemonUrl = value;
}
getPokemonsUrl(): Observable<IPokemonDetails[]>{
return this.http.get<IPokemonDetails[]>(this._pokemonUrl);
}
}
pokemon-search.component.ts
export class PokemonSearchComponent implements OnInit {
pokemons = [];
pokemonUrl: string;
constructor(private _pokemons : PokemonsService) { }
ngOnInit(){
this._pokemons.getUrl().subscribe(data => {
console.log(data);
this.pokemons = data;
});
}
sendPokemonUrlToService(value: string){
this._pokemons.setPokemonUrl(value);
}
onClick(url){
this._pokemons.setPokemonUrl(url);
console.log(this._pokemons);
}
onClickNextPokemon(url){
this._pokemons.setUrl(url);
console.log(this._pokemons);
}
}
pokemon-search.component.html
<ul *ngFor="let pokemon of pokemons.results">
<li><button (click)="onClick(pokemon.url)">{{pokemon.name}}</button></li>
</ul>
<button (click)="onClickNextPokemon(pokemons.previous)">PREVIOUS</button>
<button (click)="onClickNextPokemon(pokemons.next)">NEXT</button>
非常感谢
答案 0 :(得分:1)
通常,应在发生数据更改时更新您的UI。如果u使用changeDetection: ChangeDetectionStrategy.OnPush
作为更改检测策略,而您的数据更改未反映在用户界面中,则U可以使用标记进行检查,如下所示:
constructor(private _pokemons : PokemonsService,
private _changeDetectorRef: ChangeDetectorRef) { }
ngOnInit(){
this._pokemons.getUrl().subscribe(data => {
console.log(data);
this.pokemons = data;
this._changeDetectorRef.markForCheck();
});
}
确保此方法调用中的数据this._pokemons.getUrl()
可用。
添加您的* ngFor,如下所示。您应该循环li而不是ul
<ul>
<li *ngFor="let pokemon of pokemons.results">
<button (click)="onClick(pokemon.url)">{{pokemon.name}}</button>
</li>
</ul>