【问题标题】:NgRx Properties of Object in store is always undefined?存储中对象的 NgRx 属性始终未定义?
【发布时间】:2020-02-28 15:12:42
【问题描述】:

我目前正在使用 NgRx 8 来存储带有图像名和 url 的图像:

export default class AzureImage {
    Id: number;
    Name: string;
    Url: string;
  }

我的 Homecomponent 中有一个包含所有图像的列表,如果我单击一个图像,则会使用 ImageDetails 加载一个新组件。在 URL 中,我有图像的 id。现在我想获取 AzureImage-Object 的 ImageName。所以我打电话给商店并用 is 获取 AzureImage-Object。当我将对象打印到控制台时,我可以看到带有名称和 url 的对象。

但如果我之后调用 Object.Name,名称总是未定义。

这是组件类:

export class AzureimagedetailsComponent implements OnInit {

  constructor(private route: ActivatedRoute, private aspNetApiService: AspNetApiService, private store: Store<{ azureImages: AzureImageState }>) { }

  ngOnInit() {
    let id = +this.route.snapshot.paramMap.get('id');

    this.store.pipe(select('azureImages'))
      .pipe(
        map(store => {
          return store.AzureImages[id];
        })
      ).subscribe((k: AzureImage) => {
        console.log('Here i can see the Object with the Name',k)
        if (k !== null && k !== undefined) {
          console.log('Here is the name undefined',k.Name)
          this.aspNetApiService.analyzeImageByAzure(k.Name)
            .pipe(
              map(x => {
                console.log(x);
                this.analyzedImage = x;
              })
            )
        }
      });
      this.store.dispatch(AzureImageActions.BeginGetAzureImageAction());
  }

我是 NgRx 状态管理的新手。我是在做一些事情还是我不能访问对象的属性是正常的?

【问题讨论】:

  • 这个问题看起来与ngrx无关(就问题而言)......是k.Name还是k.name?请包含console.log('Here i can see the Object with the Name',k)的输出
  • 好的。我真的不明白。因为你写了这个,所以我检查了控制台日志。那里是“名字”。但我用“名称”定义了 AzureImage 对象。我将其更改为“名称”,现在它可以工作了。我想非常感谢:)

标签: angular undefined ngrx ngrx-store


【解决方案1】:

您需要确保您的模型与从后端或映射到前端模型返回的内容相匹配

任何一个

export default class AzureImage {
    id: number; 
    name: string; // or whatever BE returns
    url: string;
  }

API 服务中的 OR

getAll(): Observable<AzureImage[]> {
    this.http.get(...).pipe(
        map(data => data.map(d => {
            return {
                    Id: d.id,
                    Name: d.name,
                    Url: d.url
            }
        })
    )
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-08-18
    • 1970-01-01
    • 2016-05-18
    • 2020-06-21
    • 1970-01-01
    • 2018-11-16
    • 2018-01-27
    • 1970-01-01
    相关资源
    最近更新 更多