2017-08-09 39 views
1

我對http.get請求有問題。 數據在請求後顯示1秒鐘,然後消失。 component.ts:Angular 2丟失了來自http.get請求的數據

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> 
+0

有沒有在瀏覽器中發生的任何異常? – eddyP23

+0

該代碼本身似乎是正確的 – eddyP23

+0

在broser中沒有例外 –

回答

0

的問題是,我沒有給訪問API。我正在使用ASP.NET Core。我剛打開訪問我的WEB應用程序在我Startup.cs:

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(); 
    }