簡體   English   中英

如何以角度將對象從服務返回到組件

[英]How to return object from service to component in angular

我想在 ngOninit 中訪問特定的 json。 所以我在單擊編輯按鈕時有 id,在該 id 的幫助下,我從數據庫中獲取完整的對象,如表單名稱、表單 json 等。所以我想從服務中將該 json 返回給 ngOninit。

這里是服務。

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

在控制台中,我從我保存的數據庫中獲取完整的對象。

這是組件

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

就像我怎樣才能在 ngOnInit 中獲取 json。

編輯

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 中傳遞它。

這不是您應該如何訂閱可觀察對象。 在處理異步操作(例如 HTTP 請求)時,您應該閱讀文檔/教程 同時,這是我們解決您的問題的方法。

為您服務,

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

在您的 component.ts 上,我們通過調用subscribe()方法返回可觀察值。

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

您不在服務類中訂閱Observable ,而是在組件中訂閱:

在服務中,只需從您的服務方法返回Observable

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

在您訂閱服務方法返回的Observable的組件中:

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

不要訂閱內部服務,訂閱內部組件 onInit。

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM