如何从angular2中的WebMethod获取数据

Pra*_*vin 8 http angular

在使用Ajax的Javascript中

   $.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);
    }
   });
Run Code Online (Sandbox Code Playgroud)

尝试跟随angular2

  return this._http.get("AttendanceMast.apsx/GetDistinctBatch")
  .map((response) => response.toString());
Run Code Online (Sandbox Code Playgroud)

它返回

{ "_isScalar": false, "source": { "_isScalar": false }, "operator": {} }
Run Code Online (Sandbox Code Playgroud)

C#

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

1)如何在angular2中使用?

见下面的错误

在此输入图像描述

Pan*_*kar 6

你的方法只是返回Observable,它们只是作为一个函数.Observable在性质上是懒惰的.在您订阅它们之前,它们不会被执行.

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

myService.AttendanceMast().subscribe(
  data => console.log(data);
)
Run Code Online (Sandbox Code Playgroud)


Pra*_*vin 3

数据服务

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);
}
Run Code Online (Sandbox Code Playgroud)

C#

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

称呼

  this.dataService.getwithParamter().subscribe(
        tradeshows => this.getwithparamter = tradeshows,
        error =>  console.error('Error: ' +error)
    );
Run Code Online (Sandbox Code Playgroud)

打印这个变量来显示你的输出this.getwithparamter