Sending parameters to a function within the ngAfterViewInit() lifecycle method in Angular version 6

As a beginner in coding, I have created a canvas in Angular and am attempting to pass data received from my server to a function within ngAfterViewInit().

When I hard code the values I want to pass, everything works perfectly. However, if I try to pass data after receiving it from the server, I encounter an undefined error for the values inside ngAfterViewInit().

I am working on passing the following values:

seatsNum: number
rowsNum: number

To these:

var numberOfSeats = this.seatsNum
var numberOfRows = this.rowsNum

Here is the full code:

import { Component, Directive, ElementRef, AfterViewInit, Input, Renderer, ContentChild, ViewChildren, ViewChild } from '@angular/core';
import { ManageShowsService } from '../../services/shows-mananger.service';
import { Router, ActivatedRoute } from '../../../../node_modules/@angular/router';
import { Show } from '../../models/show.model';
import { DomSanitizer } from '../../../../node_modules/@angular/platform-browser';

@Component({
selector: 'app-seat-selection',
templateUrl: './seat-selection.component.html',
styleUrls: ['./seat-selection.component.scss']
})
export class SeatSelectionComponent {
show: any
tempOrderArray = new Array()
orderSeatsClient = []    
selectedSeatsClient = []
selectedSeatsServer = [{ "id": 5 }, { "id": 19 }] 

seatsNum: number
rowsNum: number


cX: number // X click coordinates
cY: number // Y click coordinates  

@ViewChild('canvas') canvasRef: ElementRef;
private canvas: any;
@Input('size') size: number;
@Input('color') color: string;
@Input() width: number;
@Input() height: number;

constructor(private el: ElementRef,
            private renderer: Renderer,
            private showService: ManageShowsService,
            private route: ActivatedRoute,
            private sanitizer: DomSanitizer) {

}

sanitize(url: string){
    return this.sanitizer.bypassSecurityTrustUrl('http://localhost:3000/' + url);
}

ngOnInit() {
    this.showService.getShowById(this.route.snapshot.params['id'])
        .subscribe(data => {
            console.log(data)
            this.seatsNum = data.showsHall[0].rows
            this.rowsNum = data.showsHall[0].seats

            this.show = {
                "hallName": data.showsHall[0].hallName,
                "movieName": data.movie[0].movieName,
                "movieImg": data.movie[0].movieImg,
                "takenSeats": data.takenSeats,
                "_id": data._id,
                "showDate": data.showDate,
                "showStartTime": data.showStartTime,
                "showEndTime": data.showEndTime,
            }
            console.log("from ts" + this.seatsNum, this.rowsNum)
        })
}

ngAfterViewInit() {
    this.canvas = this.canvasRef.nativeElement;
    this.canvas.width = 550;
    this.canvas.height = 500;
    this.draw();
}

draw() {
    var ctx = this.canvas.getContext('2d');
    ctx.font = "15px Arial";
    var seats = []                                    
    var tempOrderArray = []                        
    var orderSeatsClient = []                     
    var selectedSeatsClient = []                    
    var selectedSeatsServer = this.selectedSeatsServer
    var numberOfSeats = this.seatsNum
    var numberOfRows = this.rowsNum
    console.log("from js" + numberOfSeats, numberOfRows)
    var counter = 0    
    function make_base() {
        var base_image = new Image();
            base_image.src = ('../../../assets/img/screen2.png');
            base_image.onload = function () {
                ctx.drawImage(base_image, 75, -110);
            }
    }

Answer №1

Avoid using ngAfterViewInit in this scenario. Since you are dealing with an asynchronous call, it will take some time to fetch the data.

To resolve this issue, make sure to execute your function once the data is obtained within the subscribe() method, like so:

this.showService.getShowById(this.route.snapshot.params['id'])
.subscribe(data => {
   ...// your custom logic here
     this.canvas = this.canvasRef.nativeElement;
     this.canvas.width = 550;
     this.canvas.height = 500;
     this.draw();
}

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

JavaScript application throwing error: "require is not defined"

Currently, I am working on storing an array in a .json file using NodeJS. However, when trying to execute the code below, I encountered an error message saying require is not defined. Can someone provide some guidance on how to resolve this issue? let ans ...

The issue of innerHTML malfunctioning when multiple eventListeners are used in a JavaScript code for the "Type Ahead" feature

I am currently working on enhancing the "Type Ahead" code from the Wes Box Javascript30 course by adding my own modifications. In the original code, a single data source is used to update search suggestions based on user input. I have adapted the code to i ...

AngularJS and CSS: A Guide to Effortlessly Toggle Sliding List Elements

I am in the process of developing a drop-down menu that can be clicked. Using my custom AngularJS directive, I have successfully implemented functionality to load menu items dynamically. While I have made significant progress, I have encountered a small i ...

What is the best way to retrieve the previous URL in Angular after the current URL has been refreshed or changed

Imagine being on the current URL of http://localhost:4200/#/transactions/overview/5?tab=2 and then navigating to http://localhost:4200/#/deals/detail/ If I refresh the deals/detail page, I want to return to the previous URL which could be something like h ...

Implementing a tooltip or bubble display functionality without using the span tag or title attribute

Is there a way to display tooltips when users hover over specific text or keywords? The text is retrieved directly from the database, so adding span or div tags or title information is not an option. Are there any methods to automatically generate tooltips ...

Firestore information does not appear visible

I encountered an issue with my custom hook where I am fetching images from a Firestore collection. Everything was working smoothly until I attempted to retrieve the metadata of the images as well. The problem arose when I included the getMetaData function, ...

Material Grid adamantly refused to follow the typical horizontal layout, defying its default behavior

I recently discovered Material-UI and have been trying to get two components to display side by side. However, no matter what I try, it always ends up looking like this: https://i.stack.imgur.com/w1Wyh.png Even though it is the default behavior, the Mate ...

Display a text over a full-screen HTML5 video

Is there a way to display text on a fullscreen video in HTML? I have tried using absolute positioning for the text and relative/fixed/none positioning for the video, but it does not work when the video is in fullscreen mode. I also attempted to call the ...

How should the superclass constructor of `MatDialog` be invoked when working with multiple classes?

When dealing with multiple features in my ts file, I decided to split them into separate classes. constructor( ) { super(MatDialog); } Encountered error: Argument of type 'typeof MatDialog' is not assig ...

Tips for effectively utilizing Vuelidate to display errors selectively after the user has completed input:

I have implemented a form using Bootstrap-Vue with some Vuelidation code applied to it. <b-form @submit.prevent="onSubmit"> <input type="hidden" name="_token" :value="csrf" /> <transition-group name="fade"> <b-form ...

There is an ample amount of blank space located at the bottom of the page

There seems to be an excess of white space at the bottom of my webpage, despite my efforts to adjust margins and padding. I've inspected the elements using browser developer tools but have been unable to pinpoint the issue. var chatResponseBox = do ...

Highchart displays results for each individual line without the use of commas

I am interested in creating a chart using Highchart with three lines. The first two lines will display data similar to [4.12, 3.34, 5.45] / [3.45, 5.45, 3.23], while the third line should be displayed without any commas, showing results like [7, 4, 2]. Can ...

A Guide on Adding Excel-Like Filtering Functionality to AngularJS

I am struggling to implement a simple Excel-like filter for a table using AngularJS (v.1). I have shared my code snippet below and would appreciate any help to show filtered data in the table after checking a checkbox and clicking on the OK button. I have ...

Basic illustration of AJAX web-app, encompassing client and server components

Currently, I am immersing myself in the world of AJAX by tapping into online resources and delving into some informative books. While doing so, I discovered that AJAX is not exactly a groundbreaking technology in and of itself, but rather a method of lever ...

Having trouble converting the response into a valid TypeScript value for storage

These are the interfaces I have described: enum ProductType {current, closed, coming} export interface CurrentProductForCarousel { type_product:ProductType.current; offers: ProductMainInfo[] } export interface ProductMainInfo { id: number; disclai ...

Passing parameters from a div to a single page component in Vue.js: A complete guide

There is code that appears on multiple pages: <div id="contact-us" class="section md-padding bg-grey"> <div id="contact"></div> <script src="/dist/build.js"></script> </div> Included in main.js is: im ...

How can I pass a value from a jQuery variable to a PHP variable?

Utilizing jQuery to create a table based on the output of JSON. The JSON values are retrieved from a SoapClient, which is functioning correctly and producing the desired output. https://i.sstatic.net/vJbfW.png Now, the goal is to assign the value of the ...

There seems to be an issue with $(window).scrollTop() not functioning properly in Safari

While it works smoothly on Firefox and Chrome, there seems to be an issue with Safari. Here is the code snippet: function founders() { var scrollPos = $(window).scrollTop(); if (scrollPos == 900) { $(function() { $(".first_fall").f ...

turning off next.js server side rendering in order to avoid potential window is undefined issues

I am currently managing a private NPM package that is utilized in my Next.js project, both of which are React and Typescript based. Recently, I integrated a graph feature into the NPM package and encountered an issue where any reference to window within t ...

Having trouble with JavaScript's Date.getUTCMilliSeconds() function?

I have a straightforward question for you. Take a look at this Angular App and try to create a new date, then print the number of UTC milliseconds of that date in the console. Can you figure out why it is returning zero? ...