Heptagram
Heptagram

Reputation: 145

Angular, Interpolation properties with names containing dot

I have an HTTP GET request with a response containing properties names with dot '.' Exemple: 'first.name' and 'last.name'

So I created a class model like

export class GetUser{
   'first.name': string;
   'last.name': string;
   city: string;
}

and my request :

  private getUser(user?: User): Observable<GetUser[]> {
    return this.http.get<GetUser[]>(`${.API_URL}/user`);
  }

The request work and I have my object, but when I want use this object in my template HTML Angular I can't use the interpolation like

{{ user.first.name }}

It's doesnt work.

It's possible to make a binding with a property with a dot ?

So, I thought make a mapper or an decorator for convert the property name 'first.name' to 'firstName'

How I can make a mapper response ?

Thank

Upvotes: 0

Views: 1080

Answers (1)

Poul Kruijt
Poul Kruijt

Reputation: 71911

You can also do {{ user['first.name'] }} in the template, but most likely it's better to parse it, for readability purposes. Which could be done like this:

export class GetUser {
  'first.name': string;
  'last.name': string;
  city: string;
}

export class User {
  firstName: string;
  lastName: string;
  city: string;
}

private getUser(user?: User): Observable<User []> {
  return this.http.get<GetUser[]>(`${.API_URL}/user`).pipe(
    map((user) => parseDotProperties(user))
  );
}

export function parseDotProperties<
  T extends object = {},
  U extends object = {}
>(obj: U): T {
  return Object.keys(obj).reduce((parsed, key: string) => {
    const propertyName = key.split('.').map((part, i) =>
     i ? part.charAt(0).toUpperCase() + part.slice(1) : part
    ).join('') as keyof T;

    parsed[propertyName] = obj[key as keyof U] as any;

    return parsed;
  }, {} as T)
}

Playground Link

Upvotes: 1

Related Questions