您可以在组件内部订阅,也可以创建一个在完成后发出值的主题。
订阅组件内部
@Injectable() export class UserService { private user: User; private url: string = 'v1/user'; constructor(private restService: RestService) {} public getUser() { return this.restService.get(this.url); }
在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, []) }) ); }); }
订阅服务对象
@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; }
然后在您的组件中订阅它
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); }); }