angular - 使用从服务中获取的数据初始化响应式表单
问题描述
我正在研究角度项目。我遇到的问题是我在订阅服务中获取数据并使用行为主题传递该数据。现在在我的组件中,我正在订阅服务并获取数据并尝试预填充我的表单,但出现错误
服务.ts
publicpost= new BehaviorSubject<any>(null);
getPublicPost(){
this.http.get<UPost[]>(`https://write-your-heart-out-b338b.firebaseio.com/post/${this.uid}/public.json`)
.pipe(
map(responseData => {
const postsArray: UPost[] = [];
for (const key in responseData) {
if (responseData.hasOwnProperty(key)) {
postsArray.push({ ...responseData[key] });
}
}
return postsArray;
})
)
.subscribe(posts => {
this.publicpost.next(posts)
this.combine()
});
}
组件.ts
constructor(
private route: ActivatedRoute,
private router: Router,
public acrud: ACrudService,
private fb: FormBuilder,
) { }
ngOnInit(): void {
this.route.params
.subscribe(
(params: Params) => {
console.log(params)
this.id = +params['id'];
this.posttype=params['type']
});
this.acrud.getPublicPost()
this.PubicPost()
this.EditForm()
}
PubicPost(){
this.isFetching=true
this.allSub = this.acrud.all.subscribe(d => {
this.allPost = d
this.isFetching=false
console.log("####################", this.allPost)
,
err=>{
this.error=err
},
()=>{
console.log(this.allPost[this.id].title) // this part is not execution dont know why
this.exampleForm.patchValue(
{
title:this.allPost[this.id].title
}
)
})
}
EditForm() {
this.exampleForm = this.fb.group({
imgurl:['', Validators.required],
title: ['', Validators.required],
desc: ['', Validators.required],
category: [this.selected, Validators.required],
subcategory: [' ', Validators.required],
name: ['', Validators.required],
privacy: ["true"],
});
方法2:
PubicPost(){
this.isFetching=true
this.allSub = this.acrud.all.subscribe(d => {
this.allPost = d
this.isFetching=false
console.log("####################", this.allPost)
console.log(this.allPost[this.id].title)
this.exampleForm.patchValue(
{
title:this.allPost[this.id].title
}
)
,
err=>{
this.error=err
})
}
方法3:
PubicPost(){
this.isFetching=true
this.allSub = this.acrud.all.subscribe(d => {
this.allPost = d
this.isFetching=false
console.log("####################", this.allPost)
this.EditForm() // removing this method from ngOninit and Initiliazing here
)
err=>{
this.error=err
})
}
我能够获取数据的唯一方法是在 HTML 模板中使用插值,例如
<div class="form-group ">
<label for="comment">Title:</label>
<div class="input-style">
<input placeholder="Name" class="form-control" formControlName="title"
value={{Allpost[this.id].title}}>
</div>
</div>
解决方案
您可以使用 getRawValue() 从表单组中读取所有值,并使用 patchValue() 一次写入所有值:
// write into form
const raw = {
imgurl: 'demo',
title: 'demo',
desc: 'demo',
category: 'demo',
subcategory: 'demo',
name: 'demo',
privacy: true
};
this.formGroup.patchValue(raw);
和
// read from form:
const raw = this.formGroup.getRawValue();
如果你想一次得到所有的 http 结果,你可以使用 forkJoin:
forkJoin([
this.http.get<X>(url1),
this.http.get<whatever[]>(url2),
this.route.params
]).
subscribe(
arr => {
console.info(arr[0]);
console.info(arr[1]);
console.info(arr[1]);
}
)
请参阅:https ://rxjs-dev.firebaseapp.com/api/index/function/forkJoin
不要忘记取消订阅: https ://blog.bitsrc.io/6-ways-to-unsubscribe-from-observables-in-angular-ab912819a78f
推荐阅读
- perl - 如何在 Perl 中将用户定义的函数添加为内置函数?
- jquery - 如何通过 html 链接预先填充短信正文而不填写电话号码。在苹果手机中
- bash - hashcorp vault 递归删除
- python - 将 2 个相同大小的列表合并到一个 dicts Python 列表中
- html - 将临时表写入 SQL Server 中的 HTML 表并将其清空
- wordpress - 从jenkins管道发送post请求到wordpress的问题
- xml - xsl : 将文本转换为 xml
- c++ - 如何通过引用或指针将对象传递给构造函数?
- scikit-learn - 在 scikit-learn 中为分类任务添加协变量
- javascript - 等待 for 循环结束以在 javascript 中继续函数