在angular中,我想在按钮中的点击事件后添加一组新的API url后刷新组件这是我的密码。pokemons.services.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.comcomponent.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>
提前感谢
通常,当数据发生更改时,应该更新UI。如果你使用changeDetection: ChangeDetectionStrategy.OnPush
作为你的更改检测策略,并且你的数据更改没有反映在你的UI中,你可以使用标记来检查下面的
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>