简体   繁体   English

Angular2问题与This.http.get

[英]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. 我开始使用Angular 2,为此我在http:// localhost:8081 / ping上在IIS中本地设置了一个ASP> .NET WebApi(调用返回一个序列化为JSON对象的字符串),该方法运行得很好。

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 但是,当我尝试通过此函数进行此调用时,在实际调用中得到200,但是从handleError函数中收到以下错误

在此处输入图片说明

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? 我已经尝试过将ASP.NET WebApi实际部署到Micrsoft Azure站点,并且它的反应完全相同,而且我知道api工作正常,只是我不确定我的服务出了什么问题,这是否发生在其他任何人身上在这里还是关于问题原因的任何想法?

Harry Ninh was correct, once I enabled CORS in my ASP.NET WebApi it began working in all browsers; Harry Ninh是正确的,一旦我在ASP.NET WebApi中启用了CORS,它便开始在所有浏览器中运行。 at least the ones I mentioned in my comment above. 至少我在上面的评论中提到的那些。 Thanks Harry Ninh for your help. 感谢Harry Ninh的帮助。

I used to get same issue earlier when i used XHRBackend issue got resolved . 当我使用XHRBackend问题解决时,我曾经遇到过同样的问题。

In app.module.ts i have written like following 我在app.module.ts中写了如下

import { HttpModule, Http, XHRBackend} from '@angular/http'; 从'@ angular / http'导入{HttpModule,Http,XHRBackend};

@NgModule({. . . providers: [ HttpModule, XHRBackend, .. @NgModule({。。provider:[HttpModule,XHRBackend,..

],}

)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM