我要按表在城市中使用温度,如下所示。我还有其他硬编码的数据,但是,温度数据需要从API中获取。我正在使用给定的城市名称从API成功获取数据,但是试图弄清楚如何在表中呈现数据。
组件文件
export class HomeComponent implements OnInit {
events: Event[];
selectedEvent: any;
temperature:any;
constructor(private eventService: EventService,
private weatherService: WeatherService) { }
loadTemperature(city: string){
this.weatherService.getWeather(city).subscribe(data =>{
this.temperature = data.current.temp_c;
})
模板文件
<table class="table table-hover">
<thead>
<tr>
<td>Event Id</td>
<td>Event Name</td>
<td>Session Time</td>
<td>City</td>
<td>Temperature</td>
</tr>
</thead>
<tbody *ngFor="let event of events">
<tr (click)="onSelect(event)">
<td>{{event.id}}</td>
<td>{{event.name}}</td>
<td>{{event.time}}</td>
<td>{{event.city}}</td>
<td>{{**HERE I NEED TEMP BY CITY**}}</td>
</tr>
</tbody>
</table>
请向我建议解决该问题的方法。 我使用了以下技巧,但没有成功
<td *ngIf = "loadTemperature(event.city)">{{temperature}}</td>
<td>{{loadTemperature(event.city)}}</td>
答案 0 :(得分:1)
我想您不需要多个<div>
@if(count($errors)>0)
@foreach($errors->all() as $error)
<ul>
<li>{{$error}}</li>
</ul>
@endforeach
@endif
</div>
标签,因此您应该将 public async Task<AzureOperationResponse<AccessKeys>> RegenerateKeysWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string authorizationRuleName, RegenerateAccessKeyParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (resourceGroupName != null)
{
if (resourceGroupName.Length > 90)
{
throw new ValidationException(ValidationRules.MaxLength, "resourceGroupName", 90);
}
if (resourceGroupName.Length < 1)
{
throw new ValidationException(ValidationRules.MinLength, "resourceGroupName", 1);
}
}
if (namespaceName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "namespaceName");
}
if (namespaceName != null)
{
if (namespaceName.Length > 50)
{
throw new ValidationException(ValidationRules.MaxLength, "namespaceName", 50);
}
if (namespaceName.Length < 6)
{
throw new ValidationException(ValidationRules.MinLength, "namespaceName", 6);
}
}
if (authorizationRuleName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "authorizationRuleName");
}
if (authorizationRuleName != null)
{
if (authorizationRuleName.Length > 50)
{
throw new ValidationException(ValidationRules.MaxLength, "authorizationRuleName", 50);
}
if (authorizationRuleName.Length < 1)
{
throw new ValidationException(ValidationRules.MinLength, "authorizationRuleName", 1);
}
}
if (parameters == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "parameters");
}
if (parameters != null)
{
parameters.Validate();
}
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("namespaceName", namespaceName);
tracingParameters.Add("authorizationRuleName", authorizationRuleName);
tracingParameters.Add("parameters", parameters);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "RegenerateKeys", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceBus/namespaces/{namespaceName}/AuthorizationRules/{authorizationRuleName}/regenerateKeys").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{namespaceName}", System.Uri.EscapeDataString(namespaceName));
_url = _url.Replace("{authorizationRuleName}", System.Uri.EscapeDataString(authorizationRuleName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("POST");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(parameters != null)
{
_requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(parameters, Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<AccessKeys>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<AccessKeys>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
放在tbody
上,此外,您可以使用*ngFor
管道来获取你想要什么:
<tr>
必须更改async
函数以返回<tbody>
<tr *ngFor="let event of events" (click)="onSelect(event)">
<td>{{event.id}}</td>
<td>{{event.name}}</td>
<td>{{event.time}}</td>
<td>{{event.city}}</td>
<td>{{ loadTemperature(event.city) | async }}</td>
</tr>
</tbody>
的地方:
loadTemperature
我不完全确定这会对您的性能产生什么影响,由于Observable
,它甚至可能一遍又一遍地调用相同的api。也许添加loadTemperature(city: string): Observable<number> {
this.weatherService.getWeather(city).pipe(
map((data) => data.current.temp_c),
shareReplay(1)
});
}
可以解决此问题。
更好的方法是将温度添加到*ngFor
中。但是为了给您展示,我需要知道如何获取此trackBy
数组。
考虑到您在某处进行了硬编码,可以执行以下操作:
events
并且您需要更新模板以使用新的Observable:
events
答案 1 :(得分:0)
通常,在* ngFor中调用一个函数是一个“坏主意”(角度多次“ * paint” * ngFor)。您必须使用forkJoin一起进行所有调用并更改数组。或多或少像下面这样(注意:我不检查代码,把它当作一个主意)
AddTemperatures(events:any[])
{
//create an array of "calls" -an array of Observables-
conts obs:Observable[]=events.map(even=>{
return this.weatherService.getWeather(even.city);
})
//forkJoin realize all the calls together and
//put the result in an array, so
//result[0] becomes the temperature of events[0].city
//result[1] becomes the temperature of events[1].city ...
return forkJoin(obs).pipe(map(result=>{
//with result, for each event add the property "temperature"
events.ForEach((event:any,index)=>{
event.temperature=result[index]
})
}))
}
答案 2 :(得分:0)
这是我解决这个问题的方法。 我在主组件中创建了两个单独的组件。这是结构。
家庭组件 -EventListComponent -EventComponent
现在,我在列表组件中迭代ngFor循环,如下所示。 EventListComponent
export class EventListComponent implements OnInit {
events: Event[];
constructor(private eventService: EventService,
) { }
ngOnInit() {
this.eventService.eventsChanged.subscribe((events: Event[]) => {
this.events = events;
});
this.events = this.eventService.getEvents();
}
EventListComponentTemplate
<div class="container-fluid">
<div class="row text-center">
<div class="col-sm-2">
<b>Event ID</b>
</div>
<div class="col-sm-2">
<b>Event Name</b>
</div>
<div class="col-sm-3">
<b>Session Time</b>
</div>
<div class="col-sm-3">
<b>City</b>
</div>
<div class="col-sm-2">
<b>Temperature</b>
</div>
</div>
<div class="row">
<div class="col-sm-12">
<app-event
*ngFor="let e of events; let i = index"
[event]="e"
[index]="i">
</app-event>
</div>
</div>
</div>
我使用了数据绑定,并向事件组件提供了一个事件。 活动组件
export class EventComponent implements OnInit {
@Input() index: number;
@Input() event: Event;
temp: string;
constructor(private weatherService: WeatherService) { }
ngOnInit() {
this.loadTemperature(this.event.city);
}
loadTemperature(city: string) {
this.weatherService.getWeatherByCity(city).subscribe(data =>{
this.temp = data.current.temp_c;
})
}
}
EventComponent模板
<div class="container-fluid">
<div class="row text-center" style="cursor: pointer; margin: 15px 0;"
[routerLink]="index"
routerLinkActive="active">
<div class="col-sm-2">
{{index}}
</div>
<div class="col-sm-2">
{{event.name}}
</div>
<div class="col-sm-3">
{{event.time}}
</div>
<div class="col-sm-3">
{{event.city}}
</div>
<div class="col-sm-2">
{{temp}}C
</div>
</div>
</div>
就像在事件组件中一样,我只有一个事件,我可以通过API调用轻松地为城市分配温度。
谢谢大家的回答。
答案 3 :(得分:-1)
尝试这种方式-
loadTemperature(city: string){
return this.weatherService.getWeather(city).pipe(map(x => x.current.temp_c));
<td>{{loadTemperature(event.city) | async}}</td>