简体   繁体   中英

Similar properties in a typescript model class

I like to have data model class, which should hold same information for two persons at same time.. Eg

export class persons {
    constructor(
        public person1Name:string = '',
        public person1Age:number = 0,
        public person1Game: string ='',
        
        public person2Name:string = '',
        public person2Age:number = 0,
        public person2Game: string ='',
    ){}
}

So it has same information (ie name, age, game) for two persons.
I know, I can have a generic person model class, but problems is, I always send exactly two persons information from a angular service to the component.
In case of generic person class, I have to send an array of objects like:

Array: [person1, person2]

In that case, in service as well as in component, will be difficult to manage, because I'm using information in different ways.
More importantly, I'm sending information of two persons from service through observable.

The question is, can I have model class which represents same information for two persons as mentioned above? because I really like to avoid array of objects..
Thanks in advance..

You could have an interface where you define the data type for any person you want, without instantiating it.

export interface Person {
  id: string;
  name: string;
  age: number;
  game: string;
}

Then, just for giving you an example (I don't know exactly the requirements), you could do something like:

@Component({...})
export class MyComponent implement OnInit {
  people: Person[] = []; // an empty array of people

  constructor(private theService: TheService) {}
 
  ngOnInit(): void {
    const dave = this.getMeAPerson('Dave Morris', 12, 'Game 1');
    const dave = this.getMeAPerson('John Doe', 20, 'Game 2');

    this.people = [dave, john]; //populate as much as you want

    this.theService.sendPeople(this.people).subscribe((response) => {
        response.forEach(person => console.log('Person', person));
    })
  }

  getMeAPerson(name: string, age: number, game: string): Person {
    return {
      id: 'some-unique-id-so-you-can-identify-each-person',
      name,
      age,
      game
    };
  }
}
@Injectable({...})
export class TheService {
   constructor(private http: HttpClient) {}
  
   sendPeople(people: Person[]): Observable<Person[]> {
     return this.http.post<Person[]>('url', people).pipe(
        map(response => // do something with it)
     );
   }
}

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