2017-01-03 32 views
8

使用Ajax如何從在的WebMethod angular2

$.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); 
    } 
    }); 

獲得的數據在Javascript中嘗試以下的angular2

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

返回

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

C#

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

1)如何在angular2中使用?

看到錯誤下面

enter image description here

+2

你必須'訂閱'那種方法返回'Observable',直到那時它不會工作.. –

+0

@ Pankaj Parkar你能給我代碼什麼需要改變我的代碼 – Pravin

+0

.net項目和angular2在同一個應用服務器上 – Eswar

回答

4

的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; 
} 

呼叫

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

打印這個變量顯示你的輸出this.getwithparamter

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); 
) 
+0

嗨我試過,但檢查錯誤上面 – Pravin

+0

我搜索,但我主要使用webapi是否有可能使用webmethod,因爲它搜索路徑像url但它的文件名在錯誤 – Pravin

+0

幫我完全空白 – Pravin

0

我假設您正在使用WebService的標準配置。如果是這樣,我相信你的問題是你正在使用Angular2的內置休息功能來訪問一個WebService,也就是一個Soap服務,返回XML soap信封。因此,404.

不幸的是,與使用休息服務相比,您還有更多工作要做。 看看github上的angular2-soap。它應該讓你走上正軌。

+0

感謝您的回覆,但我得到了解決方案中已經給出的解決方案 – Pravin