我想在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请求)时,您应该阅读documentation / tutorial。同时,这就是我们如何解决您的问题。
在你的服务上,
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);
})
}