Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get data from WebMethod in angular2

Tags:

http

angular

In Javascript using Ajax

   $.ajax({
    type: "Get",
    url: "AttendanceMaster.aspx/GetDistinctBatch",
    data: "{}",
    contentType: "application/json; charset=utf-8",
    datatype: "jsondata",
    async: "true",       
    success: function(response) {

    },
    error: function(response) {
        alert("(allstudent )" + response.status + ' Error ' + response.statusText);
    }
   });

tried following for angular2

  return this._http.get("AttendanceMast.apsx/GetDistinctBatch")
  .map((response) => response.toString());

it returns

{ "_isScalar": false, "source": { "_isScalar": false }, "operator": {} }

C#

 [System.Web.Services.WebMethod]
 public static string GetDistinctBatch()
 {      
    return "welcome Angular 2";
 }

1) how to use in angular2?

See Error below

enter image description here

like image 515
User Avatar asked Jan 03 '17 04:01

User


2 Answers

Your method is just returning Observable, they will just sit as a function. Observable are lazy in nature. They wouldn't get executed until you subscribe to them.

AttendanceMast() {
   return this._http.get("AttendanceMast.apsx/GetDistinctBatch")
         .map((response) => response.toString()); //better do it response.json();
}

myService.AttendanceMast().subscribe(
  data => console.log(data);
)
like image 83
Pankaj Parkar Avatar answered Oct 16 '22 04:10

Pankaj Parkar


dataservice

getwithParamter(): Observable<JSON> {                

            this.headers = new Headers();
            this.headers.append('Content-Type', 'application/json; charset=utf-8');               

            let options = new RequestOptions({
                method: RequestMethod.Post,
                url: "AttendanceMast.aspx/HelloWorldss",                   
                headers: this.headers,
                body:{program: 'pravin'}  //same like data: "{}" in ajax
            });

           return this._http.request(new Request(options)).retry(2)
             .map((response: Response) => response.text())
            .do(data => console.log('All: ' + JSON.stringify(data)))
            .catch(this.handleError);                  

    }
  handleError(error: any) {
    console.error('An error occurred', error);
    return Promise.reject(error.message || error);
}

C#

[System.Web.Services.WebMethod]
public static string HelloWorldss(string program)
{
    return "welcome Angular" + program;
}

call

  this.dataService.getwithParamter().subscribe(
        tradeshows => this.getwithparamter = tradeshows,
        error =>  console.error('Error: ' +error)
    );

print this variable showing your output this.getwithparamter

like image 28
User Avatar answered Oct 16 '22 05:10

User