How to return object from service to component in angular

前端 未结 3 797
终归单人心
终归单人心 2020-12-12 06:55

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 , f

相关标签:
3条回答
  • 2020-12-12 07:27

    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.

    On your service,

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

    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;
      })
    }
    
    0 讨论(0)
  • 2020-12-12 07:31

    You don't subscribe to the Observable in the service class, but instead in the component:

    In the service, just return the Observable from your service method:

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

    In the component you subscribe to the Observable returned by the service method:

    ngOnInit() {
      const id = this.route.snapshot.paramMap.get('id');
      this.dataService.GetFormById(+id).subscribe(data => {
        console.log(data);
      });
    }
    
    0 讨论(0)
  • 2020-12-12 07:36

    Don't subscribe inside service, subscribe inside component 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);
        })
    }
    
    0 讨论(0)
提交回复
热议问题