如何将对象从服务返回到组件中的角度 [英] How to return object from service to component in angular

查看:43
本文介绍了如何将对象从服务返回到组件中的角度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想访问ngOninit中的特定json.因此,我在单击编辑"按钮时获得了ID,并借助该ID,我正在从数据库中获取完整的对象,如表单名称,表单json等.因此,从服务中,我想将该json返回给ngOninit.

I want to access particular json in ngOninit. So i have id on click in edit button and with the help of that id i am getting complete object from database like form name , form json which etc. So from the service i want to return that json to ngOninit.

这是服务.

    GetFormById (id: number) {
    return this.httpClient.get<FormTemplate[]>(this.API_URL + 
    "GetFormTemplate/" + id).subscribe(data => {
      console.log(data);
      return data;
    });
    }

在控制台中,我从已保存的数据库中获取完整的对象.

In console i am getting complete object from database which i have save.

这是组成部分

    ngOnInit() {
    const id = this.route.snapshot.paramMap.get('id');
    var json = this.dataService.GetFormById(+id);
    }

就像我如何在ngOnInit中获取json.

like how can i get json in ngOnInit.

修改

ngOnInit() {
const id = this.route.snapshot.paramMap.get('id');
this.dataService.GetFormById(+id).subscribe(response => {
  console.log(response);
  const temp = response['TemplateJson'];
     })

initJq();
  var formData = '[{"type":"header","subtype":"h1","label":"Inquiry"},{"type":"paragraph","subtype":"p","label":"Paragraph content"},{"type":"text","label":"First name","name":"text - 1554220470561","value":"Vipul","subtype":"text"},{"type":"date","label":"Date Field","className":"form - control","name":"date - 1554220484446","value":"2019 - 04 - 25"},{"type":"button","label":"Send Inquiry","subtype":"button","className":"btn btn - primary","name":"button - 1554220480284","style":"primary"}]';

  this.formBuilder = (<any>jQuery('.build-wrap')).formBuilder({ formData });

 // Sample code to handle promise to get for data on page load directly
  this.formBuilder.promise.then(formBuilder => {
    console.log(formBuilder.formData);
  });
}

就像我临时使用的json一样,我都希望以var formData传递它.

like whatever json i got in temp i want to pass it in var formData.

推荐答案

这不是您应该从可观察对象订阅的方式.您应该阅读文档/

This is not how you should subscribe from observables. You should read up the documentation/tutorial when it comes to handling asynchronous operations (such as HTTP requests). Meanwhile, this is how we can fix your issue.

为您服务

GetFormById (id: number) {
  return this.httpClient.get<FormTemplate[]>(`${this.API_URL}GetFormTemplate/${id}`);
}

在您的component.ts上,我们通过调用subscribe()方法返回可观察的值.

On your component.ts, we return the observable value by calling the subscribe() method.

ngOnInit() {
  const id = this.route.snapshot.paramMap.get('id');
  this.dataService.GetFormById(id).subscribe(response => {
    console.log(response);
    const templateObj = response.TempleteJson;
  })
}

这篇关于如何将对象从服务返回到组件中的角度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆