Using Angular to send data to a WCF JSON endpoint

I've been trying to send a request to a WCF JSON service endpoint from Angular, but I haven't had any luck so far. The service has been tested through other methods and is functioning properly for the specified URL.

When checking with Firebug, I can see the request being sent like this:

NetworkError: 400 Bad Request - "

Angular code snippet

app.service('UserService', function ($http) {
this.GetLoginStatus = function (AuthenticateRequest) {
    $http({
        url: APIURL + "/Authenticate",
        method: "POST",
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
        },
        params: AuthenticateRequest,
        data: {
            'Code': 'test data'
        }
    });
};

WCF Iservice Configuration

[WebInvoke(RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json,
Method = "POST",
BodyStyle = WebMessageBodyStyle.Wrapped)]
[OperationContract]
AuthenticateResponse Authenticate(AuthenticateRequest Request);

Definition of the Request object

[DataContract]
public class AuthenticateRequest
{
    [DataMember]
    public String UserName { get; set; }
    [DataMember]
    public String Password { get; set; }
}

Answer №1

I completed this task by converting a JavaScript object into a string.

    Service.js

        angular.module('myModule').factory('serviceFac', ['$http', '$q', 
function (a, b) 
    {   var taskMergeServiceNameSet = "WebServuice.svc/Tasks/SetTasks";
            return {
                setTasksMerge: function (taskIds, action) {

                 var objArray = '';
                 var obj = {
                        taskIds: taskIds,
                        action: action,
                        userName: "ss"
                  };
                 objArray = new Array();
                 objArray.push(obj);
                 var deferred = b.defer();
                 a({
                   url: taskMergeServiceNameSet,
                   method: 'POST',
                   headers: { 'Content-Type':'application/json; charset=utf-8'},
                   data: JSON.stringify(objArray)
                  }
                  ).sucess(function (data) { deferred.resolve(data) })
                  .error(function (msg, code) { deferred.reject(msg) });    
                    return deferred.promise;
                }
            }
        }]);

Service Contract

ServiceContract Interface

[ServiceContract]
public interface ITasks
{
   [OperationContract]
    [WebInvoke(Method = "POST",RequestFormat=WebMessageFormat.Json ,
      ResponseFormat =   WebMessageFormat.Json, 
      UriTemplate = "Tasks/SetTasksForMerge")]
    string CreateNewTaks(valObj[] values);        
}

[DataContract]
public class valObj
    {
    [DataMember]
    public string taskIds { get; set; }
    [DataMember]
    public string action { get; set; }
    [DataMember]
    public string userName { get; set; }
    }

Found a useful post here that provided valuable insight. Feel free to reach out if you have success in sending a JSON string as well.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Steps for configuring gulp-watch with a TFS project to prevent the EPERM problem

In my current project, I am utilizing angularJS with bower for managing dependencies on the web UI and npm for handling dependencies like bower, gulp, karam, etc. This project is stored in TFS and we are using VS2013 as we have a Web API v2 project that re ...

Incorporating JavaScript to dynamically load an HTML page into an iframe

I am attempting to have each option load a unique page within a frame <!DOCTYPE html> <html> <head> <script> function selectCountry() { var mylist=document.getElementById("country"); document.getElementById("frame").src=mylist.opti ...

adding a JavaScript module to a handlebars template

I have a few different files that I'm working with: In the server.js file, I have the following code: app.get('/main/:id', function(req, res) { res.render('main', { products: products }); }) Within the main.hbs file, I have ...

Send the user's context id as a header when making a request to a REST

In my current setup, I have implemented two applications - a Laravel REST API and an Angular front end, each residing on different domains. This is a multi-tenant application where users can be associated with one or multiple organizations and have the abi ...

Is there a way to check for invalid string literals within a string?

Looking for a way to test for invalid (unclosed) strings within a given string? This regex might help: /"[^"\\]*(?:\\[\S\s][^"\\]*)*"|'[^'\\]*(?:\\[\S\s][^'\\]* ...

JavaScript code must be tailored to reference a JS file based on the specific environment, whether it be Production, Development, or staging

I need to determine which .js file to refer based on the URL of Prod, Dev, and QA environments. For Production URLs (domain.com and www.domain.com), I should refer to prod.js file. For Dev and QA URLs (dev.domain.com and staging.com), I should refer to s ...

Troubleshooting Next.js and NextAuth.js Authentication Redirect Issue

I am experiencing a problem with authentication in my Next.js application using NextAuth.js. The issue specifically pertains to the redirection after successful login. Here is an overview of my setup: NextAuth.js Configuration (app/api/auth/[...nextauth.js ...

Having trouble accessing the text in a paragraph using JavaScript executor and web driver

On a particular website, there is: <p id="tempid" value="Manual Effect">testing the test</p> String value = (String)((JavascriptExecutor) this).executeScript("return window.document.getElementById('tempid').value"); System.out.pr ...

"Authentic JavaScript Universal Time Coordinated (UTC) Date

I've been struggling to keep my dates in UTC within my JavaScript application. Surprisingly, the Date's getTimezoneOffset() method does not return a value of 0, which I expected it to do. This seems crucial for accurately converting dates between ...

JSON error on Android: X not found in the list

Encountering the No Value For visibility error in my JSON parsing app has left me puzzled. Despite successfully logging all data to LogCat, they are not being added to my list. What could be causing this discrepancy? Here is the structure of my class: pu ...

Material-UI and TypeScript are having trouble finding a compatible overload for this function call

Currently, I'm in the process of converting a JavaScript component that utilizes Material-ui to TypeScript, and I've encountered an issue. Specifically, when rendering a tile-like image where the component prop was overridden along with an additi ...

convert and transform XML data into JSON format

I have been working with nodejs-expressjs and I received a response in raw XML format. My goal is to convert this raw XML into either a JavaScript array or a JSON array so that I can extract the domain name along with its status. I want to display this inf ...

The window.load() function seems to be malfunctioning as the event is not being triggered. There are no error

I'm struggling with getting the window.load() event to trigger on this specific website. The issue arose last night and despite there being no visible js or php errors, pinpointing the root cause has proven to be quite challenging. In syrp.home.main ...

Is there a foolproof method to authenticate form submissions using Javascript/Ajax instead of relying on PHP?

Currently, my process of handling HTML form submissions is done in PHP where I submit the form to a PHP file that: Verifies against a cookie created at page load to prevent CSRF. Includes a require_once() function for validation purposes. Executes other ...

Generate a progress indicator upon user clicking a hyperlink

I am looking to implement a loading bar that appears when the user clicks a link. Additionally, I need to upload data (via Ajax) into div#work if needed, followed by displaying the loading bar. Once the data is successfully uploaded, I want the script to s ...

Searching through a JSON array with a Mongoose query

I am a beginner in node.js and just started using mongoose along with node.js. Schema: var userSchema = new mongoose.Schema({ username: String, password: String, phone_no : String, email: String, name:String, dob: {type: Date, ...

Unleashing the power of TypeScript with Solid JS Abstract Class

Why am I getting an undefined error for my calcUtilisation method when using an Abstract Class as the type in createStore? Is there a way to utilize a type for the data along with a method within the same class for createStore? abstract class Account { ...

Access the elements within arrays without using the square brackets

I am trying to access data from a list, but I am having trouble using square brackets []. The getTalonPaie function calls the get method from the HttpClient service and returns an observable with multiple values. However, when I try to store these values i ...

Using RxJS v5 for Sending a POST Request with Parameters

Snippet of my RxJS code: .mergeMap(action => { const user = store.getState().user; return ajax.post(`${config.API_BASE_URL}/api/v1/rsvps`, { rsvp: { meetup_id: action.payload, user_id: user.id, } }) .map(action => calenda ...

"Troubleshooting: ngForm.controls returning undefined value in Angular application

Trying to test this HTML code in Angular: <form name="formCercarUsiari" #formCercarUsuari="ngForm" class="tab-content"> <input #inputNif class="form-control input-height" maxlength="100" type="text" placeholder="Indiqui NIF" name="nif" i18n-pla ...