我们可以对 Angular 中的 API 数据进行 if Check 吗?

Can we do a if Check to API data in Angular?

这是mt TS文件,其中_services.liveclasses_api()指向service.ts,用API获取。

this._services.liveclasses_api().subscribe((result)=>{
  console.log(result);
  this.liveclasses = result.data.classes;
})

这里的要点是,从 API 我们得到 PHY、Chem 等主题。我们必须打印 Physics、Chemistry 等...

<p 
  *ngIf="d.subject == 'CHEM'" 
   class="sess-subject">
   <span>
    <img src="/assets/images/chemistry.png" class="sesssub-icon"alt="" />
    </span>CHEMISTRY
</p>

<p 
  *ngIf="d.subject == 'PHY'" 
  class="sess-subject">
  <span>
   <img src="/assets/images/physics.png" class="sesssub-icon"alt="" />
  </span>Physics
</p>

所有其他科目也是如此。有没有另一种方法,我可以从 API 主题代码中打印主题名称?在 Angular 模板上没有 ngIf

根据您的问题,我了解到您的 API 为您提供了 'PHY'、'CHEM' 等值...

因此,与其像那样检查多次,不如像这样重构该逻辑:

// somewhere else in your project, you could have an `enum`
// for getting the values 

//subject.utils.ts for example

export enum mySubjects = {
   'CHEM': 'CHEMISTRY',
   'PHY': 'PHYSICS'
   ....
}

// back in your component, you could handle it like this:
import { MySubjects } from '../subject.utils';
...
...
...

getSubjects(): Observable<YourTypeHere> {
 return this._services.liveclasses_api().pipe(
    map((response) => MySubjects[response.data.classes])
  );
}

getImageSource(mySubject: string): string {
  return `/assets/images/${mySubject.toLowerCase()}.png`
}
<ng-container *ngIf="(formatSubjects$ | async) as subject">
  <p   
     class="sess-subject">
     <span>
     <img 
       [src]="getImageSource(subject)" 
       class="sesssub-icon"alt="" />
     </span>{{ subject }}
  </p>
</ng-container>