Search code examples
angularundefinedngrxngrx-store

NgRx Properties of Object in store is always undefined?


I'm currently using NgRx 8 to store images with imagename and url:

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

I have a list of all Images in my Homecomponent, if i click on one Image, a new component is loaded with ImageDetails. In the URL i have the id of the image. Now i want to get the ImageName of the AzureImage-Object. So i call the store and get the AzureImage-Object with the is. When i print the Object to the console, i can see the Object with name and url.

But if i call Object.Name afterwards the Name is always undefined.

Here is the Component-Class:

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

I'm new to NgRx for State Management. Am i midding something or is it normal that i can' access properties of objects?


Solution

  • You need to make sure your model matches what is returned from the backend OR map to the front end model

    EITHER

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

    OR in API service

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