【发布时间】:2020-05-19 15:05:31
【问题描述】:
我正在从事 Angular 项目。我遇到的问题是我在订阅服务中获取数据并使用行为主题传递该数据。 现在在我的组件中,我正在订阅服务并获取数据并尝试预填充我的表单,但我收到了错误
service.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()
});
}
component.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>
【问题讨论】:
标签: angular typescript angular2-template angular-reactive-forms angular-forms