html Angular 上的可观察数据未显示

eiee3dmh  于 2022-12-16  发布在  Angular
关注(0)|答案(1)|浏览(120)

我试图通过API请求检索的Observable的数据到一个组件变量,以显示它,但我只是不能使它工作。请帮助,这是我的代码。问候,
类型脚本服务:请求API获取可观察性

export class ServeurService {
  
  serverCharacter = 'https://cegep.fdtt.space/v1/characters';
  serverSecret = 'https://cegep.fdtt.space/v1/secret';
  personnages: any[] = [];
  persoName = '';

  constructor(private http_client: HttpClient) { }

  getPersonnage(): Observable<ICharactere[]> {
    return this.http_client.get<ICharactere[]>(this.serverCharacter).pipe(retry(4));
  }

  getAllInfosById(id: string): Observable<ICharactere> {
    const myUrl = 'https://cegep.fdtt.space/v1/character/' + id;
    return this.http_client.get<ICharactere>(myUrl)?.pipe();
  }

  setPersonnageName(name: string) {
    this.persoName = name;
  }

  getPersonnageName():string {
    return this.persoName;
  }

  getPersonnages() {
    this.http_client.get<any>('https://cegep.fdtt.space/v1/characters').subscribe({
      next: (val) => {
        val.data.forEach((element: { data: any; }) => {
        this.personnages.push(element);
        });
      }
    });
    return this.personnages;
  }

  getPersonnageById(id: string) {
    const persoSelectionne = this.getPersonnages().find((x: { id: string; }) => x.id === id);
    return persoSelectionne;
  }

  getPersonnageIdByName(name: string) {
    const persoSelectionne = this.getPersonnages().find((n: {name: string; }) => n.name === name);
    console.log("perso name service", persoSelectionne)
    return persoSelectionne.id; 
  }

类型脚本组件:将Observable传递给变量

export class StatsComponent implements OnInit {
  
  myCharactere!: any;
  statLookup = [
    { key: 'str', prefix: $localize`str`, suffix: $localize`enght`, couleur: 'bg-danger' },
    { key: 'dex', prefix: $localize`dex`, suffix: $localize`terity`, couleur: 'bg-primary' },
    { key: 'con', prefix: $localize`con`, suffix: $localize`stitution`, couleur: 'bg-warning' },
    { key: 'int', prefix: $localize`int`, suffix: $localize`elligence`, couleur: 'bg-success' },
    { key: 'sag', prefix: $localize`wis`, suffix: $localize`dom`, couleur: 'bg-info' },
    { key: 'cha', prefix: $localize`cha`, suffix: $localize`risma`, couleur: 'bg-dark' }
  ];
  constructor(public myService: ServeurService) { }

  ngOnInit(): void {
    this.myService.getAllInfosById(this.myService.getPersonnageIdByName(this.myService.getPersonnageName())).subscribe(result => {
    this.myCharactere = result
   });
   console.log("stats component perso", this.myCharactere)
  }

  getModifier(stat: number): string {
    const mod = Math.floor((stat-10)/2)
    return (mod<0)?'-':'+'+ mod.toString();
  }
}

HTML:显示变量

<div class="row text-center text-light bg-secondary mt-2  bg-transparent">
    <div class="row mt-5">
        <div class="col-2" *ngFor="let stat of statLookup">
            <div class="{{stat.couleur}} mx-xxl-4 mx-2 mx-md-1 rounded-4">
                <div class="fw-bold">{{stat.prefix}}<span class="d-none d-lg-inline">{{stat.suffix}}</span>
                </div>
                <div class="h2">
                    {{myCharactere && myCharactere.statistics && myCharactere.statistics[stat.key] ? getModifier(myCharactere.statistics[stat.key]) : ''}}
                </div>
                <div class="">
                    {{myCharactere?.data.statistics[stat.key]}}
                </div>
            </div>
    </div>
</div>

如果有帮助的话,这里也有一个模型:

export interface ICharactere {
    error: string;
    data: {
    id: string;
    name: string;
    statistics: { [ key : string ]: number }
    race: string;
    player: string;
    classe : string;
    sousclasses: string;
    level: number;
    background: string;
    synopsis: string;
    image: string;
    health: number;
    currentHealth: number;
    traits: {
        trait: string;
        description: string;
    }[];
    // Should be computed
    armorClass: number;
    initiative: number;
    speed: number;
};
}
aor9mmx1

aor9mmx11#

这里你混淆了一些基本概念。首先,你同步调用getPersonnages(),而它正在进行一个HTTP调用,这是一个异步操作。我理解你想做什么,但是如果你打算在搜索结果中使用可观察性,那么我建议你让你所有的函数调用都保持一致。下面是一个例子:

getPersonnages(): Observable<any> {
  return this.http.get<any>('https://cegep.fdtt.space/v1/characters');
}

getPersonnageIdByName(name: string) {
  return new Observable(observer => {
    this.getPersonnages().subscribe(
      (results => {
        observer.next(results.data.find(x => x.name === name))
        observer.complete();
      })
    )
  }) 
}

现在您可以搜索所需的ID值,如下所示:

this.getPersonnageIdByName("Michel Michaud").subscribe(
      (searchResult => {
        // here I can get the id
        const id = searchResult.id;
      })
    );

相关问题