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

Time:12-19

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 painpoint 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'" ><span>
<img src="/assets/images/chemistry.png" alt="" />
</span>CHEMISTRY</p>

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

Like wise for all other Subjects. Is there anyother Apporach to this, where i can print subject Name form API Subject Code ? without the ngIF on Angular template?

CodePudding user response:

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   
     >
     <span>
     <img 
       [src]="getImageSource(subject)" 
       alt="" />
     </span>{{ subject }}
  </p>
</ng-container>
  • Related