Imagine a scenario where I have a user service with information about the currently logged-in user in my Angular application. Within this context, there exists a model called Sell
which includes a field representing the id
of the user who creates a new instance of the Sell
object. Is there a method to incorporate (I'm unsure if "incorporate" is the best term to use here) the user service within the model so that when the constructor is invoked, the Sell object automatically captures and assigns the user's id?
For instance:
user.service.ts
...
@Injectable()
export class UserService {
private _id: string = 'some_id';
get id(): string {
return this._id;
}
}
sell.model.ts
export class Sell {
userId: string;
price: number;
...
constructor() {
// some way to access userService here
this.userId = this.userService.id;
}
}
some.component.ts
import { Component } from '@angular/core';
import { Sell } from '../models/sell.model';
@Component({
...
})
export class SomeComponent {
newSell() {
let sell = new Sell();
// I aim for the model itself to automatically assign the user id to its object.
console.log(sell.userId) // some_id
}
}