Looking for the most efficient method to populate a form with data from a service in Angular 5. My goal is to keep component code to a minimum and have the variable-data stored within services rather than components.
The content is loaded through a secondary service by the main service.
Sample Service:
@Injectable()
export class UserService {
private user: User;
private url: string = 'v1/user';
constructor(
private restService: RestService
) {
this.restService.get(this.url).subscribe(
res => {
this.user = res;
}
);
}
public getUser(): User {
return this.user;
}
Sample Component:
export class UserComponent implements OnInit {
private form: FormGroup;
constructor(
private userService: UserService
) {}
ngOnInit(): void {
// Initialize an empty form
this.form = new FormGroup({
email: new FormControl()
})
);
// Populate the form with values from the service
this.form.patchValue(this.userService.getUser());
}
If I introduce a delay (like 10 seconds using setTimeout) before executing patchValue(), everything works fine, but that's clearly not ideal.
Is there a way to determine when the service code has been fully loaded, without resorting to using Observables?
I appreciate any suggestions or insights!