【问题标题】:Initilaize reactive form with the data get from service使用从服务中获取的数据初始化响应式表单
【发布时间】: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>

这也是我的 cconsole 日志的图像 我可以看到我的控制台第一次出现空白数组

【问题讨论】:

    标签: angular typescript angular2-template angular-reactive-forms angular-forms


    【解决方案1】:

    您可以使用 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

    【讨论】:

    • 但是我的主题并没有一次发出所有的值,而是我得到了三个控制台日志,所以我应该如何将我的最后一个主题值提供给表单控件
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-06-10
    • 2013-07-18
    • 2019-08-29
    • 2019-05-13
    • 2019-12-07
    • 2015-05-22
    • 2013-02-16
    相关资源
    最近更新 更多