使用从服务获取的数据初始化反应形式

问题描述 投票:0回答:1

我正在从事有角度的项目。我陷入了一个问题,即我要在其中订阅的服务中获取数据并使用行为Subject传递该数据。现在,在我的组件中,我正在订阅服务并获取数据,并尝试预填充表单,但出现错误

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"],

    });

Approach2:

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
    })
}

Approach3:

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>

这也是我的控制台日志的图像enter image description here我可以看到我的控制台第一次是空白的,空白的]

angular typescript angular2-template angular-reactive-forms angular-forms
1个回答
0
投票

您可以使用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();
© www.soinside.com 2019 - 2024. All rights reserved.