API调用中错误处理更改的问题

时间:2019-05-02 14:38:16

标签: javascript angular data-binding

我对Angular还是陌生的,但对一般开发人员来说不是。做一个个人项目来尝试学习Angular的功能,我正在尝试处理一个api调用以主动更改html代码。下面有我的代码示例。我现在正在调用pokemon API并显示基本信息,我要做的就是使它成功,因此,如果响应返回错误,则找不到页面。我只是不知道在Angular中处理此问题的最佳方法,因此不胜感激。

为进一步说明,我已经能够弹出错误消息,问题是直到取消订阅并且我不知道确切的执行时间之前,我认为它无法正常工作。

根据请求:https://stackblitz.com/edit/angular-hwchtb

Pokemon.Component.HTML
<div class="container-fluid" style="text-align: center">

    Pokemon Name:<input type="text" [(ngModel)]="Pokemon">

<button (click)="searchForPokemon()">Search</button>
<div *ngIf="response;else noresponse">
    <p>Name: {{response?.name}}</p>
    Possible Abilities:
    <ul>
    <li *ngFor="let a of response?.abilities">{{a.ability.name}}</li>
    </ul>
    Learnable Moves:
    <ul>
    <li *ngFor="let m of  response?.moves">{{m.move.name}}</li>
    </ul>
</div>

<ng-template #noresponse><h3>No Pokemon of that name found</h3></ng-template>
</div>

Pokemon.Component.TS

export class PokemonComponent implements OnInit {
  Pokemon: string = "";
  response: any;
  error: any;
  constructor(private http: HttpClient){
  }
  searchForPokemon(value:string){
    this.http.get('https://pokeapi.co/api/v2/pokemon/' + 
    this.Pokemon.toLowerCase())
    .subscribe(
      (response)=> this.response = response,
      (err) => this.error = err)          
  }

1 个答案:

答案 0 :(得分:0)

将您的html更改为此:

<div *ngIf="response && !(error && error.length>0)">
    <p>Name: {{response?.name}}</p>
    Possible Abilities:
    <ul>
        <li *ngFor="let a of response?.abilities">{{a.ability.name}}</li>
    </ul>
    Learnable Moves:
    <ul>
        <li *ngFor="let m of  response?.moves">{{m.move.name}}</li>
    </ul>
</div>
<div *ngIf="error && error.length>0" #noresponse><h3>No Pokemon of that name found</h3></div>
</div>

在您的ts文件中:

Pokemon: string = "";
  response: any;
  error:string="";
  constructor(private http: HttpClient){
  }
  searchForPokemon(value:string){
    this.error='';
    this.http.get('https://pokeapi.co/api/v2/pokemon/' + this.Pokemon.toLowerCase())
    .subscribe(
      (response)=> {this.response = response},
      (err) => this.error = err.message)          
  }

Here working demo