I am tormented by the question: where I should locate my calculated properties in angular project?
For example: I have model, service to get model and component to show model.
person.model.ts:
export class Person {
firstName: string;
lastName: string;
}
person.service.ts:
export class PersonService {
// inject http: HttpClient
get(id) {
return this.http.get<Person>(`api-endpoint/person/${id}`);
}
}
person.component.ts
@Component({
selector: 'app',
template: `
<div>
<input [value]='person.firstName'>
<input [value]='person.lastName'>
</div>
`,
providers: [ PersonService ]
})
export class AppComponent {
person: Person;
// inject personService: PersonService
ngOnInit() {
personService.get(1).subscribe(p => this.person = p);
}
}
And now I need fullName
to show it into template under my input fields.
Option 1. If you google 'calculated properties angular' you will most likely find examples with calculated properties in the component iteself.
@Component({
selector: 'app',
template: `
<div>
<input [value]='person.firstName'>
<input [value]='person.lastName'>
<span>{{ fullName }}</span>
</div>
`,
providers: [ PersonService ]
})
export class AppComponent {
person: Person;
get fullName() {
return `${this.person.firstName} ${this.person.lastName}`
}
// inject personService: PersonService
ngOnInit() {
personService.get(1).subscribe(p => this.person = p);
}
}
But is this the right place for such code? What if we would like to reuse this property in other components, services and etc?
Option 2. I personally want to extend person.model.ts
.
export class Person {
firstName: string;
lastName: string;
get fullName(): string {
return `${this.firstName} ${this.lastName}`
}
}
@Component({
selector: 'app',
template: `
<div>
<input [value]='person.firstName'>
<input [value]='person.lastName'>
<span>{{ person.fullName }}</span>
</div>
`,
providers: [ PersonService ]
})
export class AppComponent {
person: Person;
// inject personService: PersonService
ngOnInit() {
personService.get(1).subscribe(p => this.person = p);
}
}
But then we face with another problem. Our personService
returns object without this getter at all.
So what should I do? Do I need to create new instance of person.model.ts
and then assign our response to it or maybe I need another model at all, something like person.view-model.ts
?
Thanks for your time :D