Alik Chebotar
Alik Chebotar

Reputation: 563

Angular2 http.get from external API

I can't figure out how to rewrite this AngularJS $http.get to Angular2:

$scope.toggle = function() {
 $http.get('http://example.com?operation=getEmployeeData', {
    params: {
      data: JSON.stringify({
        params: {
          firstName : 'John',
          lastName  : 'Doe',
          empType   : 'Administrative',
          orgUnit   : 'Management',
          lang      : 'Eng'
        }
      })
    }
  }).then(function(data) { $scope.staff = data }

This how the url with parameters looks like:

http://example.com?operation=getEmployeeData&data={"params":{"firstName":"John","lastName":"Doe","empType":"Administrative","orgUnit":"Management","lang":"Eng"}}

How I do it in Angular2? Thank you!

Upvotes: 1

Views: 1440

Answers (2)

Gourav Bhatia
Gourav Bhatia

Reputation: 196

This is the example for post/get. just use method as post or get its depend on your requirement.

you need to replace the methodname with your method name which you are calling.

 private url = "http://example.com";

 methodname(resource1: String,resource2: String,resource3: String,resource4: 
 String,resource5: String){

 let body = JSON.stringify({"firstName":resource1,"lastName":resource2,
 "empType":resource3,"orgUnit":resource4,"lang":resource5});

let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers, method: "post/get" });

 return this.http.get/post(this.url,body,options)
        .map(this.extractData)
        .catch(this.handleError);
}

Upvotes: 1

Tinwor
Tinwor

Reputation: 7973

In Angular2 Http.GET is very similar to AngularJS but for passing url parameters you must use URLSearchParams inside @angular/http package.
What you want do:

let params: URLSearchParams = new URLSearchParams();
params.set("data",JSON.stringify({
        params: {
          firstName : 'John',
          lastName  : 'Doe',
          empType   : 'Administrative',
          orgUnit   : 'Management',
          lang      : 'Eng'
        }
      }));
//Make the call and return an observable
 return this.http.get(SomeVar.MY_URL, params)
      .toPromise()
      ...

Upvotes: 2

Related Questions