Firebase - Accessing data for a specific item

Apologies for the lengthy question. I have a collection of events that I retrieve like this:

export class HomePageComponent implements OnInit {

  events: FirebaseListObservable<EventModel[]>;

  constructor(
    private authService: AuthService,
    private router: Router,
    private db: AngularFireDatabase
  ) {
    this.events = db.list('/events');
  }

  ngOnInit() {
  }

}

The events are shown in the following format:

<md-card *ngFor="let event of events | async">
    <a [routerLink]="['event', event.slug]"><img class="event-img" src="http://lorempixel.com/30/30" />{{ event.name }}</a>
</md-card>

The event.component is structured as follows:

export class EventComponent implements OnInit {

  event: Object;
  name: String;

  constructor(db: AngularFireDatabase, route: Router) {

    const eventQuery = db.list('/events', {
      query: {
        orderByChild: 'slug',
        equalTo: 'event-name'
      }
    }).subscribe(data => {
      this.event = data[0];
    });

  }

  ngOnInit() {
  }

}

The this.event object contains all relevant details and the correct data is being retrieved. It has the following structure:

Object {category: "category", description: "description", googleMap: "map", guests: Object, name: "Event name"…}
category: "category"
description: "description"
googleMap: "map"
guests: Object
name: "Event name"
slug: "event-name"
venue: "The venue"
$exists: function ()
$key: "-xxxxxxxx"
__proto__: Object

However, when attempting to display {{event.name}}, an error is encountered:

ERROR TypeError: Cannot read property 'name' of undefined
at Object.eval [as updateRenderer]

Additional inquiry:

Given that the event information is already available in HomePageComponent, is it possible to pass this data to EventComponent for display? Doing so may eliminate the need for an extra database query.

Answer №1

Utilize the secure operator ?

<md-card *ngFor="let activity of adventures | async">
    <a [routerLink]="['activity', adventure?.url]"><img class="adventure-img" src="http://lorempixel.com/30/30" />{{ adventure?.title }}</a>
</md-card>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error message: Missing "@nestjs/platform-express" package when performing end-to-end testing on NestJS using Fastify

Just set up a new NestJS application using Fastify. While attempting to run npm run test:e2e, I encountered the following error message: [Nest] 14894 - 11/19/2021, 10:29:10 PM [ExceptionHandler] The "@nestjs/platform-express" package is missi ...

Error TS2345: The argument provided, which is of type 'Promise<ReadonlyArray<Object>>', cannot be assigned to a parameter that must be of type 'T | PromiseLike<T> | undefined'

My goal is to return the ReadonlyArray<> in my promise so that I can send it back to the original method that called 'dispatchToThisProcess'. This abstraction allows for potential future updates to multiple processes. Below is the code snip ...

organize the values based on their priority using reactjs

I'm facing a challenge involving two arrays of objects: array1 and array2. I need to display only three values from both arrays, with priority given to array1. The requirements are as follows: if array1 contains 3 elements, all three should be shown. ...

Extending Mongoose's capabilities with header files for the "plugin" feature, utilizing the .methods and .statics methods

My task is to develop Typescript header files for a script that enhances my Mongoose model using the .plugin method. The current signature in the Mongoose header files looks like this: export class Schema { // ... plugin(plugin: (schema: Schema, opt ...

Mismatched data types for function arguments

const x: Example = { toY: (y: Maple) => { return y.p; } }; interface Example { toY: (y: Pine) => void; } interface Pine { c: string; } interface Maple extends Pine { p: boolean; } Despite the warning for interface names ...

What is the best way to eliminate square brackets from keys within an array of objects in TypeScript?

I am currently working on a task to eliminate all square brackets from the keys in the entries field within an array of objects: data: [ {title: "Title1", entries: { 'Entry1': 333333, '[ABC]Entry2': 1234, 'Entry3' ...

Exploring bugs in Angular 14 through unit testing

After generating a new Angular project using the CLI ng new ..., I encountered an error when running npm test. The error appeared in the browser: and in the console as well: I haven't made any additional changes to the project. I tested with Node ve ...

Issue with RouterLink functionality in Angular 6

While following a Brad Traversy tutorial on coding, I implemented the instructions exactly as given. Below is my 'app.module.ts' file. import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/c ...

Angular error TS2322 arises when attempting to assign a type of 'Observable<{}>' with the share() operator

Currently diving into Angular 5, I've been exploring the Observable/Observer pattern to facilitate event sharing and data changes among subscribers. Below is a snippet of the code in question: ... @Injectable() export class NidoService { ... eve ...

How to handle multiple formData input in NestJS controller

How can I create a controller in Nest.js that accepts two form-data inputs? Here is my Angular service code: public importSchema(file: File, importConfig: PreviewImportConfig): Observable<HttpEvent<SchemaParseResponse>> { const formData = ...

Tips for transfering variables from an electron application to the backend of an Angular project

My goal is to develop a website and desktop application using the same code base. However, due to some minor differences between the two platforms, I need a way for my Angular app to distinguish whether it has been called from the web or from Electron. I& ...

Error encountered: TypeScript module 'angularfire2/interfaces' not found in Ionic 3 with angularfire2-offline plugin

Encountering an error while trying to set up angularfire2-offline: [16:02:08] typescript: node_modules/angularfire2-offline/database/database.d.ts, line: 2 Cannot find module 'angularfire2/interfaces'. L1: import { Angula ...

Perform an action after the Ngx Bootstrap modal has been hidden

My modal features a login button: <button type="button" (click)="save()" class="btn btn-primary"> login </button> Upon clicking the button, my desired outcome is to: first hide the modal, and second navigate to another route. However, ...

ngx-bootstrap - Not Triggering On Hide Event

Having trouble triggering a function in my Angular component when closing a modal from ngx-bootstrap. No matter what method I use, I can't seem to catch the event. The event I want to trigger is simple - just need to see it in the console for now: // ...

The blank screen mystery: ionic and Google maps integration not playing nice

I've been struggling to integrate Google Maps into my web application. Unfortunately, all I see is a blank screen with no errors. Here's the current code snippet that I have. It seems like there might be an issue with the mapElement variable, but ...

Querying data conditionally with Angular rxjs

I have a json file that contains multiple arrays structured like this: { A[] B[] C[] ... } This is the query I am using: myFunction():void{ this.apiService.getData() .pipe( map((response: any) => response.A), // to access to the &ap ...

Formatting dates in Angular 2 and handling them in MongoDB with Express

I am currently working with Angular 2 and ExpressJS along with MongoDB. I have a date format that is being retrieved as 2016-06-02T14:20:27.062Z, but I need to display it in the format 06/02/2016 14:20:27 Express: In models/user.js: var userSchema = Sch ...

Having difficulty obtaining a delegation token through Auth0

I am currently working on an Angular2 application and I have integrated Auth0 for authentication. I successfully set up my Auth0 service by following the example provided here. However, I am facing an issue with obtaining a delegation token from Auth0 to ...

The argument type 'MatSort | null' cannot be assigned to the parameter type 'MatSort' in this scenario

When attempting to retrieve sorted data from MatTableDataSource, I used the following code: this.source = this.dataSource.sortData(this.dataSource.filteredData,this.dataSource.sort); Unfortunately, I encountered an error message: Argument of type ' ...

Using Typescript: ForOf Iteration with Unknown Value Types

My journey began with a quick peek at this particular inquiry. However, the approach discussed there utilized custom typing. I am currently iterating over object entries using a for-of loop. Here's a snippet of the values I'm dealing with below. ...