In Razor Component
it's not needed to @inject
See the example below:
<div class="row">
<div class="col-4">
<label for="cities">Choose city</label>
<input type="text" class="form-control" id="citiy" @bind="@cityName" />
</div>
<div class="col-3">
<button class="btn btn-primary" @onclick=@GetWeather>Get weather for @cityName</button>
</div>
</div>
<div class="row">
<div class="col-8 offset-2">
<pre id="json"><code>@ResultStr</code></pre>
</div>
</div>
And the @code
part
@code {
string cityName = "";
string ResultStr= "...";
string reqUrl => $"http://api.openweathermap.org/data/2.5/weather?q={cityName}&APPID=appID";
async Task GetWeather()
{
try
{
HttpClient client = new HttpClient();
ResultStr= "...";
var response = await client.GetAsync(reqUrl);
if (response.IsSuccessStatusCode)
ResultStr= await response.Content.ReadAsStringAsync();
else
ResultStr= response.ReasonPhrase;
}
catch (Exception ex)
{
ResultStr= ex.ToString();
}
}
}
That worked for me.. =)
HttpClient'
notnew HttpClient ()
– Batangas