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

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

问题描述

我想在 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);
  });
}

就像我在 temp 中得到的任何 json 一样,我想在 var formData 中传递它.

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

推荐答案

这不是你应该订阅 observables 的方式.您应该阅读文档/教程 处理异步操作(例如 HTTP 请求).同时,我们可以通过这种方式解决您的问题.

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天全站免登陆