I seem to have a simple scenario but I can't get it to work... I have an ASPX page with code behind. I want to access the Web Methods in the code behind. To do this I added a subscriber in my app.component.ts that calls the service which returns an observable. The service should call my web method. Here's my code:
service.component.ts
import { Injectable } from '@angular/core';
import { Http, Response, RequestOptions, RequestMethod } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
@Injectable()
export class GetDataService {
headers: any;
constructor(private _http: Http) {
}
WebMethodExample(): Observable<string> {
return this._http.get("Default.aspx/WebMethodExample").map(
(response: Response) => response.toString()
);
}
}
app.component.ts (subscriber)
import { Component, OnInit } from '@angular/core';
import { GetDataService } from './Components/service.component';
@Component({
selector: 'my-app',
template: `<h1>Hello {{name}}</h1>`,
providers:[GetDataService]
})
export class AppComponent {
name = 'Angular 2 (From component)';
constructor(private _get:GetDataService) { }
ngOnInit(): void {
console.log("In OnInit");
this._get.WebMethodExample().subscribe((data) => console.log(data));
}
}
Code behind (Default.aspx.cs)
using System;
using System.Web.Services;
namespace Angular2Demo10
{
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public static string WebMethodExample()
{
return "Sent from WebMethodExample";
}
}
}
When I run this, I get the following in the console: "Response with status: 200 OK for URL: null". I'm not sure why it isn't getting the URL. Any help is appreciated.
EDIT: Dependencies:
"dependencies": {
"@angular/common": "~2.1.1",
"@angular/compiler": "~2.1.1",
"@angular/core": "~2.1.1",
"@angular/forms": "~2.1.1",
"@angular/http": "~2.1.1",
"@angular/platform-browser": "~2.1.1",
"@angular/platform-browser-dynamic": "~2.1.1",
"@angular/router": "~3.1.1",
"@angular/upgrade": "~2.1.1",
"bootstrap": "3.3.7",
"core-js": "^2.4.1",
"es5-shim": "^4.5.9",
"es6-shim": "^0.35.3",
"reflect-metadata": "^0.1.8",
"rxjs": "5.4.3",
"systemjs": "0.19.39",
"zone.js": "^0.6.25"
},
Looking at all the other examples, have you tried setting the headers correctly, and using POST instead of a GET (I know this is weird).
Also notice we use .json
for the response instead of .tostring
WebMethodExample(): Observable<string> {
var headers = new Headers();
headers.append('Content-Type', 'application/json');
var content = {};
return this._http.post("Default.aspx/WebMethodExample",
content, {
headers: headers
}).map(
(response: Response) => response.json()
);
}