我不确定我是否理解为什么我的订阅不能正确完成。
这里是服务:
import { Injectable } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { Subject, Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class FormService {
private $formSubject: Subject<FormGroup> = new Subject<FormGroup>();
private testForm: FormGroup = this.fb.group({
foo: [null, Validators.required],
bar: [null, Validators.required]
});
constructor(
private fb: FormBuilder
) {
this.$formSubject.next(this.testForm)
}
getForm(): Observable<FormGroup> {
console.log('It gets to the getForm in the service...')
return this.$formSubject.asObservable();
}
}
这是应该订阅表单的组件:
import { Component, OnInit } from '@angular/core';
import { FormGroup } from '@angular/forms';
import { Subscription } from 'rxjs';
import { FormService } from './app-form.service';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit {
isLoading: boolean = false;
private formSub: Subscription;
form: FormGroup;
constructor(private formService: FormService) {}
ngOnInit(): void {
this.isLoading = true;
this.formSub = this.formService.getForm()
.subscribe(
(form: FormGroup) => {
console.log(form);
this.form = form;
this.isLoading = false;
}
)
}
ngOnDestroy(): void {
this.formSub.unsubscribe();
}
}
我创建了一个Stackblitz,用于复制问题:https://stackblitz.com/edit/angular-trd3iq
对于标准行为,我希望变量isLoading
设置为false,并且dom可以将其反映出来(带有'done!')。
我也希望在component.ts中获得console.log
进行打印。
编辑:我只是更改了BehaviorSubject的Subject,它起作用了……我不确定是否完全理解为什么它不能如前所述地工作。
private $formSubject: Subject<FormGroup> = new BehaviorSubject<FormGroup>(this.testForm);