Tomo
Tomo

Reputation: 434

How to reference to a controller in another project with AngularJS $http url?

This is how I do it if the C# controller is in the same project:

$http({
    method: 'GET',
    url: '/api/SomeController/SomeMethod',
    headers: { 'Content-Type': 'application/json' }

I'm building a SPA, so I want my AngularJS stuff and the WebApi stuff to be in their own projects.

How it's done if the controller is in another project inside the solution?

Upvotes: 2

Views: 2006

Answers (2)

Renan Ferreira
Renan Ferreira

Reputation: 2150

You need to inform a full url, like:

http://localhost:5376/api/SomeController/SomeMethod

and in production, change to the IP or domain.

I like to create two constants files in my project:

URL

angular.module('app')
    .constant('URL', {
        local : 'http://localhost:54341/api',
        dev : 'http://...',     
        hom : 'http://...', 
        prod : 'http://...'
    });

Config:

angular.module('app')
    .constant('CONFIG', {
        env: 'local'
    });

And use like this:

var url = URL[CONFIG.env] + '/anotherPath';

You will likely have problems with POST, PUT (...) request. If so, search for CORS and pre-flight problems.

Upvotes: 1

FKutsche
FKutsche

Reputation: 402

Your url has to match your url of the Web API. Your problem will be that the port of your localhost will change everytime you start your webserver. What you can do is setting this port.

For this you just go to the properties of your Web API project, choose the tab "Web" and then mark "Use Visual Studio Deployment Server" and enter a port.

If you take something like "1337" you can make your calls in Angular like that:

$http({
    method: 'GET',
    url: 'localhost:1337/api/SomeController/SomeMethod',
    headers: { 'Content-Type': 'application/json' }

if would really suggest you to store a base url somewhere in your javascript code, so when you deploy your page some time soon, you'll just need to change one variable.

I hope this helps you

Upvotes: 1

Related Questions