Search code examples
angularangular12

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


This is mt TS file, in which _services.liveclasses_api() points to service.ts with API Get.

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

The pinpoint in here is, from API we get Subjects as PHY, Chem, etc.. and we Have to Print as Physics, Chemistry, etc...

<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>

Likewise for all other Subjects. Is there another approach to this, where I can print the subject Name from API Subject Code? Without the ngIf on Angular template?


Solution

  • Base on your question, I understand that your API is giving you values such as 'PHY', 'CHEM', etc...

    So, instead of checking multiple times like that, you could refactor that logic like this:

    // 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>