Home > Software design >  Angular How convert result API with only value to Object with only one primitive type
Angular How convert result API with only value to Object with only one primitive type

Time:07-13

I have many api in backend and want creat front Angular but how api return only the result ["domain1","domain2"] and i need to transform this llist String[] to Domain[], with

export interface Domain{
    name:string;
}
    this.domainService.getAll().subscribe((data: String[])=>{
      data.forEach((value: String, index: number, array: String[]) => {
        let domain:Domain;
        domain.name = value;
        this.domains.push(domain);
      }
      )    })  
//The variable 'domain' is used before being assigned

CodePudding user response:

Try this:

export interface Domain{
  name: string;
}

this.domainService.getAll().subscribe((data: string[])=>{
  const mappedDomaing: Domain[] = data.map(x => ({name: x}));
  this.domains.push(...mappedDomaing);
})

Changes:

  1. data: String[] => data: string[]
  2. no need for a loop, you can use something more fancy like .map. Less code is better

About your error: //The variable 'domain' is used before being assigned

That is due to.. Really, domain needs to be initialized first before you try to access its properties by domain.name.

const domain: Domain = {
  name: value // Not sure about value, value is String and name is string, typescript compiler is not happy about that
};

Also, Angular is doing great with Observables, you should give them a try, your way of populating domains array is not very good, you can do more with less code with Observables, RxJs and AsyncPipe

CodePudding user response:

I change String to string and use that

data.forEach((value: string, index: number, array: string[]) => {
        let domain:Partial<Domain> = {};
        domain.name = value;
        this.domain.push(domain as Domain);
     }
);
  • Related