Ram
Ram

Reputation: 39

How to use below HTTP request to get data from server

enter image description hereI am new to angular I was given HTTP get service url to get the data from server How can I subscribe it and get the data.

/dashboard/graphics-chart/v1/{roleId}.

below is the method i have written in service file

  getgraphdata(defaultroleID): Observable<any> {
    return this.apiService.get(WebServiceUrl.dashboard.getPiechartData + '/' + defaultroleID)
      .pipe(map(data => data));
  }

How can I subscibe it in TS file.

Upvotes: 1

Views: 136

Answers (3)

Barremian
Barremian

Reputation: 31125

Subscribe to it as you would to any other Observable. To obtain parameters from the current URL, subscribe to paramMap of the ActivatedRoute. The following component makes your HTTP request whenever the role ID changes.

Component:

import { ActivatedRoute } from '@angular/router';

export class AppComponent implements OnInit {
  constructor(
    private dashservice: DashService, 
    private _route: ActivatedRoute ) { }
}

ngOnInit() {
  // get role ID from activated route
  this.route.paramMap.subscribe(
    (params: ParamMap) => { this.getchartdata(params.get('roleId')); }
  );
}

// use roleId 'default' if no parameters are passed
private getchartdata(roleId = 'default') {
  this.dashservice.getgraphdata(roleId).subscribe(
    response => {
      // handle response
    },
    error => {
      // handle error
    }
  );
}

Also seeing that you don't transform your data in the HTTP call, you could remove .map and return the HTTP response directly.

getgraphdata(defaultroleID): Observable<any> {
  return this.apiService.get(WebServiceUrl.dashboard.getPiechartData + '/' + defaultroleID);
}

Upvotes: 0

NikNik
NikNik

Reputation: 2301

You can subscribe in the following way in your component and to read the roleId, you can inject the route.

constructor(
    private yourService: YourService,
    private route: ActivatedRoute,
) { }

yourFunction() {
    let roleId = this.route.snapshot.paramMap.get('roleId');
    this.yourService.getgraphdata(roleId )
      .subscribe(result => ...do something with result);
}

Upvotes: 0

AbdurrahmanY
AbdurrahmanY

Reputation: 883

Define your service in component constructor and call your servis method as following:

this.yourServiceName.getgraphdata(this.defaultroleID).subscribe(res=>{
   console.log(res)
});

Upvotes: 1

Related Questions