【问题标题】:Angular 8 Subscribe not getting the return data from serviceAngular 8订阅未从服务获取返回数据
【发布时间】:2020-06-23 03:11:26
【问题描述】:

在将 ID 传递给服务并在我的SERVER 上获取数据后,我想将数据修补到我的表单中,但我没有得到任何数据。这是我的代码

addForm: FormGroup;
  ngOnInit(){
    const routesParams=this.routes.snapshot.params;


    this.addForm=this.formBuilder.group({
      Title:['',[Validators.required,Validators.minLength(1)]],
      Body:['',[Validators.required,Validators.minLength(1)]],
      Author:['',[Validators.required,Validators.minLength(1)]],
    })
     console.log(routesParams.post_id);

    this.blogService.getBlogbypost_id(routesParams.post_id).subscribe((data:any)=>{
      this.addForm.patchValue(data);

    });
  }

我的service.ts的代码

getBlogbypost_id(id:number){
  return this.http.get<cBlog[]>(this.updateUrl+id);
}

我也在服务器上获取数据,但在 subscribe((data: any)) 上没有获取数据

【问题讨论】:

  • 你应该使用解析器。
  • console.log(this.updateUrl+id) 并检查您正在访问正确的 URL 并确保返回类型

标签: angular angular2-observables subscribe rxjs-observables


【解决方案1】:

尝试以这种方式修补价值 - 我不知道你的 data 结构是什么样的,然后我在路上写了这个,但你会明白的 - 看看:

this.blogService.getBlogbypost_id(routesParams.post_id).subscribe((data:any)=>{
    this.addForm.patchValue({
        Title: data.title,
        Body: data.body,
        Author: data.author
    });
});

patchValue 并没有真正捕捉到嵌套错误,并且您有时无法知道发生了什么,正如文档中所说的 https://angular.io/guide/reactive-forms

希望这会有所帮助!

【讨论】:

  • 很高兴听到这个消息
【解决方案2】:

您好,修改如下代码:

    getBlogbypost_id(id:number): Observable<cBlog[]>{
      return this.http.get<cBlog[]>(this.updateUrl+id);
    }



 this.blogService.getBlogbypost_id(routesParams.post_id)().subscribe((data:any)=>{
      console.log(data);
      this.addForm.patchValue(data);
    });

让我知道结果如何!

【讨论】:

    猜你喜欢
    • 2019-05-27
    • 1970-01-01
    • 2016-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多