从服务获取的数据初始化响应式

时间:2020-05-19 15:05:31

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

我正在从事角度项目。我陷入了一个问题,即我在那里获取服务中的数据并使用行为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"],

    });

方法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>

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

1 个答案:

答案 0 :(得分: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();

如果要一次获取所有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

相关问题