填写服务中的反应式初始数据

时间:2019-05-17 23:17:19

标签: angular angular7 angular-reactive-forms

使用Angular 7和Reactive表单,我在组件上具有以下内容:

ngOnInit() {

  this.postForm = this.formBuilder.group({ 
    categoryId: [''],  
    title: [''],
    content: ['']
  });

}

getPost(postId: number) : Observable<Post> {

  return this.postService.getByPostId(postId);

}

PostService的GetByPostId方法如下:

public getByPostId(postId: number): Observable<Post> {

  return this.httpClient.get<Post>(`posts/${postId}`);

}

postService返回一个Post,其接口为:

interface Post {
  id: number;
  categoryId: number;
  title: string;
  content: string;
}

从getPost返回的内容中填写表单数据的正确方法是什么?

1 个答案:

答案 0 :(得分:0)

最好的方法是使用let fs = [] // You define i via LET in the for-loop block score for(let i=0; i<10; i++){ fs.push( // You push an annonymous function definition wich has a reference of i in the same block scope // i retains its lexical scope in for loops function(){ console.log(i) } ); } fs.forEach( // You call f which has a reference inside to the i from the for loop f => f() );方法:

patchValue

更多信息:here