简体   繁体   中英

Property 'isAdmin' does not exist on type 'User'.ngtsc(2339)

<td>{{ user.isAdmin }} &nbsp;&nbsp;&nbsp;&nbsp;</td>

I intended to add the isAdmin field with RxJS to the User interface, in the function down below (file is user.service.ts):

getUsers(): Observable<User[]>{
    return this.http.get<User[]>(`${this.apiUrl}/users`)
    .pipe(
      map(users => users.map(user => ({
        ...user,
        name: user.name.toUpperCase(),
        isAdmin: user.id === 10
      })))
    );
  }

The interface down below is the one used to process data (file is user.ts):

export interface User {

    id?: number;
    name: string;
    username: string;
    email: string;
    address: Address;
    phone: string;
    website: string;
    company: Company;
     
}

Since I apparently wrote it correctly, where else can the problem stem from and how can I solve it?

Thank you in advance!

Its a pretty common pattern to enrich/modify your data received from your datasource with information needed in your application. That means the interface/type of the datastructure will change:

getUsers(): Observable<EnrichedUser[]>{
    return this.http.get<User[]>(`${this.apiUrl}/users`)
    .pipe(
      map(users => users.map(user => ({
        ...user,
        name: user.name.toUpperCase(),
        isAdmin: user.id === 10
      })))
    );
  }

export interface User {
    id?: number;
    name: string;
    username: string;
    email: string;
    address: Address;
    phone: string;
    website: string;
    company: Company;    
}

export interface EnrichedUser extends User {
  isAdmin: boolean;
}

In the map you convert the original User typed objects into EnrichedUser objects which have an additional property isAdmin . In this simple example the interfaces can extend from each other.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM