I'm searching for the best way to fill a form with data from a service in Angular 5. I wanted to have as little component code as possible, thats my variable-data is stored within the services and not the component.
My services actually load the content via a second service.
Example 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;
}
Example Component:
export class UserComponent implements OnInit {
private form: FormGroup;
constructor(
private userService: UserService
) {}
ngOnInit(): void {
// Initalize the empty form
this.form = new FormGroup({
email: new FormControl()
})
);
// Fill the form with values from the service
this.form.patchValue(this.userService.getUser());
}
When I actually wait for a time (like 10 seconds with setTimeout) and then execute the patchValue() everything works, but obviously that is not optimal.
Is there a way to know when the code in the service is loaded, aside from going to take a sledgehammer to crack a nut and using an Observable?
I'm thankful to any input.
You can subscribe inside your component instead, or you could create a subject that emits the values once done.
Subscribing inside component
@Injectable()
export class UserService {
private user: User;
private url: string = 'v1/user';
constructor(private restService: RestService) {}
public getUser() {
return this.restService.get(this.url);
}
In component.ts
export class UserComponent implements OnInit {
private form: FormGroup;
userSub: Subscription;
user: string;
constructor(
private userService: UserService
) {}
ngOnInit(): void {
userSub = this.userService.getUser()
.subscribe( (res) => {
this.user = res;
// Initalize the empty form
this.form = new FormGroup({
'email': new FormControl(this.user, [])
})
);
});
}
Subscribing to a subject in service
@Injectable()
export class UserService {
userRetrieved: new Subject<User>();
private user: User;
private url: string = 'v1/user';
constructor(
private restService: RestService
) {
this.restService.get(this.url).subscribe(
(res) => {
this.user = res;
this.userRetrieved.next(this.user);
}
);
}
public getUser(): User {
return this.user;
}
Then in your component, subscribe to it
export class UserComponent implements OnInit {
userSub: Subscription;
private form: FormGroup;
constructor(
private userService: UserService
) {}
ngOnInit(): void {
// Initalize the empty form
this.form = new FormGroup({
email: new FormControl()
})
);
this.userSub = this.userService.userChanged
.subscribe((res: User ) => {
//Code to update and Fill the form with values from the service
// this.form.patchValue(res);
});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With