Avoid using the keyword let
in that specific context. Consider one of the following alternatives:
private payload = new User(); // if you want to restrict access outside the class
public payload = new User(); // if external classes need direct access
Your question was:
How can I set the properties in the model after creating an instance of it?
The ideal place for doing this in components is the ngOnInit
lifecycle hook. This code is executed by Angular once your component is initialized (before the view is rendered)
export class MyComponent implements OnInit {
private someProperty:int;
ngOnInit(){
this.someProperty = 7;
}
}
If there are multiple tasks to perform, simply call your initialization functions within ngOnInit
. In your example, you have a service. Since it's not a component, it cannot utilize this lifecycle hook. If you already know the property values while writing the code (as evident from your second screenshot), you can set them directly:
private payload:User = {
email: '...',
token: '...'
}
However, if the values are determined through a function, create an initializer function and call it from the consuming components.
@Injectable()
export class UserService {
private isInitialized:boolean = false;
private payload:User;
public init(){
// The initialize() method should only run once
if(this.isInitialized) return;
this.payload = new User();
this.payload.email = '...';
this.payload.token = this.someFunction();
// Prevent the initialize() method from running again
this.isInitialized = true;
}
private someFunction(){return 'token';}
}
In any component, it's enough to call this.userService.init()
before using it.
Note 1: To have a single global instance of a service, it must be listed in the providers
array of your main AppModule
and not provided elsewhere.
Note 2: If initialization involves asynchronous operations, such as fetching data from a remote source, ensure to handle promises or observables and wait for resolution before utilizing the service.