Search code examples
angularangular2-servicesangular2-http

Angular2 issue with This.http.get


I am beginning to play with Angular 2 and to do so I set up a ASP>NET WebApi hosted locally in IIS at http://localhost:8081/ping (the call returns a string serialized as a JSON Object) which works perfectly well.

This is my service,

import { Injectable }    from '@angular/core';
import { Headers, Http } from '@angular/http';

import 'rxjs/add/operator/toPromise';

@Injectable()
export class TempService {

    constructor(
        private http: Http
    ){}

    ping(): Promise<string>{
        return this.http.get('http://localhost:8081/ping')
            .toPromise().then(res => res.json() as string)
            .catch(this.handleError);
    }

    private handleError(error: any): Promise<any> {
        alert(error);
        return Promise.reject(error.message || error);
    }
}

However, when I attempt to make this call through this function, I get a 200 in the actual call however I get the following error from the handleError function

enter image description here

I have tried actually deploying the ASP.NET WebApi to an Micrsoft Azure site and it reacts the exact same, and I know for a fact the api is working I just am not sure what is wrong with my service, has this happened to anyone else on here or any ideas on the cause of the issue?


Solution

  • Harry Ninh was correct, once I enabled CORS in my ASP.NET WebApi it began working in all browsers; at least the ones I mentioned in my comment above. Thanks Harry Ninh for your help.