Angular 2从http.get请求中丢失了数据

时间:2017-08-09 12:17:12

标签: angular http get

我遇到了http.get请求的问题。 请求后数据显示1秒钟,然后消失。 component.ts:

http.get('http://localhost:52875/api/clients/1').subscribe(result => {
        this.client = result.json();
    });

http.get('http://localhost:52875/api/client_balances/1').subscribe(result => {
        this.cash = result.text();
    });

component.html:

<p *ngIf="!client"><em>Loading...</em></p>
<form *ngIf="client">
        {{client.first_name}}
        {{client.last_name}}
<br />
        {{cash}}
<br />
<a class="alert-link" [routerLink]="['/cash/add']">Add</a>
<a class="alert-link" [routerLink]="['/cash/out']">Out</a>
</form>

1 个答案:

答案 0 :(得分:0)

问题是我没有授予访问API的权限。我使用的是ASP.NET Core。我刚刚在Startup.cs中打开了对我的WEB应用程序的访问:

public void ConfigureServices(IServiceCollection services)
    {
        // Added this:
        services.AddCors(options =>
        {
            options.AddPolicy("AllowSpecificOrigin",
                builder => builder.WithOrigins("http://localhost:50749"));
        });
        //
        Other code
        //
        services.AddMvc();
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env, 
    ILoggerFactory loggerFactory)
    {
        loggerFactory.AddConsole(Configuration.GetSection("Logging"));
        loggerFactory.AddDebug();
        // Added this:
        app.UseCors("AllowSpecificOrigin");

        app.UseMvc();
    }