1

我正在尝试通过选择器将组件中的位置变量绑定到商店中的另一个变量,其中 ngrx v13 有角度,但是当我将带有属性的变量放入 HTML 中时出现错误:

错误消息:“可观察”类型上不存在属性“名称”

那是我的代码:

应用程序选择器.ts

import { createSelector } from "@ngrx/store";

export const CurrentLocationSelector=(state:AppState) => state.currentLocation;
export const getCurrentLocation = createSelector(
    CurrentLocationSelector,
    (currentLocation: any) => {
      return [...new Set(currentLocation)];
    }
);

那是我的 AppState:

interface AppState{
    darktheme:boolean;
    temperatureUnit:string;
    currentLocation:any; // object with the current location
    locationAutoComplete:any[]; // array that contains the result from the autocomplete
    locationCurrentWeather:CurrentItem | null;
    Forecast5Days:ForecastItem[];
    Favorites:FavoriteItem[];
    loading:boolean;
    getData:boolean;
}

在我的组件中我写道: current-weather.component.html

         <div class="left">
             <span class="locationName">{{location$.name}}</span>
             <span class="date">{{currentFullDate}}</span>
             <div class="weatherDescription">
                 <img [src]="imageCurrentWeather" class="weatherIcon">
                 <div class="weatherText">{{CurrentWeather.WeatherText}}</div>
             </div>
             <h1 [innerHTML]="CurrentWeather.Temperature + ' ' + currentUnit"></h1>
         </div>

在我的current-weather.component.ts我写

  location$ = this.store.pipe(select(CurrentLocationSelector))
4

2 回答 2

0

您可以使用异步管道,因为 location$ 是可观察的。

<span class="locationName">{{(location$ | async).name}}</span>

当前天气.component.html

     <div class="left">
         <span class="locationName">{{(location$ | async).name}}/span>
         <span class="date">{{currentFullDate}}</span>
         <div class="weatherDescription">
             <img [src]="imageCurrentWeather" class="weatherIcon">
             <div class="weatherText">{{CurrentWeather.WeatherText}}</div>
         </div>
         <h1 [innerHTML]="CurrentWeather.Temperature + ' ' + currentUnit"></h1>
     </div>

异步管道的参考

于 2021-12-04T07:31:44.417 回答
0

所以这里的问题是您将变量分配location$observable。这意味着它不是代表您的数据的单个对象,而是可以在任何时间点代表您的数据的多个值的集合。将其视为数据流。

这意味着您需要在给定点获取对象的值——通常是当前时间点。要.subscribe()对其进行此调用以侦听传入的 observables 并.select通过以下方式侦听包含您想要的数据的特定选择器:

在您的current-weather.component.ts文件中:

let $location;
this.store.select(CurrentLocationSelector).subscribe(location => {
  $location = location; // put a debug break point here to see your value get updated
});
于 2021-11-29T23:52:38.760 回答