Typescript Error: Trying to access a property that is undefined

I am a beginner in typescript and believe that the issue I am facing is related to typescript. Currently, I am working on an Ionic app where I have a function setwall() being called from home.html. The setwall() function is defined in home.ts. However, when I run the Ionic app, it displays:

Runtime Error
Uncaught (in promise): TypeError: Cannot read property 'wallpaper' of undefined 
TypeError: Cannot read property 'wallpaper' of undefined"

Below is the code from my home.ts file:

import { Component } from '@angular/core';
import { NavController, Platform } from 'ionic-angular';
import { ListPage } from '../list/list';

declare var window: any;
@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {
  constructor(public navCtrl: NavController, private platform: Platform) {
  }
  goPage1() {
    this.navCtrl.push(ListPage);
  }
  setwall() {
    this.platform.ready().then(() => {
      window['plugins'].wallpaper.setImage("assets/img/3.jpg");
    });
  }
}

Furthermore, here is the code from home.html:

<ion-header>
  <ion-navbar>
    <button ion-button menuToggle>
      <ion-icon name="menu"></ion-icon>
    </button>
    <ion-title>Wallfeed</ion-title>
  </ion-navbar>
</ion-header>

<ion-content class="card-background-page">

    <ion-card (click)="goPage1()">
      <img src="assets/img/1.png"/>
      <div class="card-title">São Paulo</div>
      <div class="card-subtitle">41 Listings</div>
    </ion-card>

    <ion-card>
      <img src="assets/img/2.jpg"/>
      <div class="card-title">Amsterdam</div>
      <div class="card-subtitle">64 Listings</div>
    </ion-card>

    <ion-card (click)="setwall()">
      <img src="assets/img/3.jpg"/>
      <div class="card-title">San Francisco</div>
      <div class="card-subtitle">72 Listings</div>
    </ion-card>

    <ion-card>
      <img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQ16sUl5EqIDeuP1AjIX6ESSbAFAcS2-JLr4znf-extlfIr47Ni"/>
      <div class="card-title">Madison</div>
      <div class="card-subtitle">28 Listings</div>
    </ion-card>

  </ion-content>

If you need more information, please refer to the link for the cordova plugin: https://github.com/fbsanches/cordova-plugin-wallpaper Thank you.

Answer №1

Here is an example to try out.

declare var window: any;

@Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
constructor(public navCtrl: NavController,private platform: Platform) {

 }

 goPage1(){
   this.navCtrl.push(ListPage);
  }

 setwall(){
    this.platform.ready().then(() => {
    window.plugins.wallpaper.setImage("./assets/img/3.jpg"); //Modified part
  });
 }
} 

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

What is the best approach for conducting unit tests on model interfaces with TypeScript?

export interface Person { fullName: string; } What is the best way to create unit tests for the above interface and ensure that Karma includes it in the code coverage report? I attempted to assert properties by creating an object, but it seems that K ...

Error in TypeScript: Angular Jasmine - The argument given as type 'string' cannot be assigned to a parameter expecting type 'never'

Currently, I am in the process of writing test cases for Angular using Jasmine 3.6.0 and TypeScript 4.1.5 with "strict": false set in my tsconfig.json file. One particular task involves spying on a component method called 'close', and following ...

Why is my custom 404 page failing to load after building my Next.js application?

I recently set up a custom 404 page for my Next.js app and wanted to test it locally before deploying to the server. To do this, I used the "serve" package to host the project on my local machine. However, when I tried navigating to a non-existent page, th ...

Allowing Cross-Origin requests in Spring BootLet's configure the

Every time I attempt to communicate with my backend using my Angular client, I encounter a common error message when trying to perform POST, PUT, and DELETE requests: Access to XMLHttpRequest at 'http://localhost:8087/categories' from origin &ap ...

Issue with NgRx Testing: Callback in subscribe method fails to update during testing

I am currently working on testing a component that is responsible for editing shopping list items. Upon first loading, the component receives state values through store.select, which are: editedIngredient: null, editedIngredientIndex: -1 Based on these ...

Tips for preventing the impact of angular mat-panel position changes on matdialog

In my Angular project, I utilized Matmenu and MatDialogModule. I needed to change the position of mat-menu, so I achieved this by adding the following snippet to my .scss file. ::ng-deep .cdk-overlay-pane { transform: translate(78%, 10%); } However, ...

Exported data in Vue3 components cannot be accessed inside the component itself

Essentially, I'm working on creating a dynamic array in Vue3. Each time a button is clicked, the length of the array should increase. Below is the code snippet. <div class="package-item" v-for="n in arraySize"></div> e ...

Aggregating and organizing all TypeScript files within the project while preserving the file hierarchy

Looking to utilize a task runner such as Grunt or Gulp to compile TS to JS files in various locations within the project folder. The goal is to ensure that the outputted JS files are placed in the same directory where the project will look for them alongsi ...

While working with Ngrx/effects, an error with code TS2345 occurred. The error message stated that the argument is of type 'Product[]', which cannot be assigned to a parameter of type

When I compile my code, I encounter the following issue (despite not finding any errors in the browser console and the application functioning properly). An error occurs in src/app/services/product.service.ts(15,9): The type 'Observable<Product> ...

Alter the value by clicking a button within the DynamicRadioGroupModel in ng Dynamic Forms

I am working with ng-dynamic-form (version 6.0.4) and NG Bootstrap in Angular 6. I have a simple question. When a button click event is triggered, I want to change the value in DynamicRadioGroupModel by using the "setValue()" method. However, I am facing ...

Typescript - type assertion does not throw an error for an invalid value

When assigning a boolean for the key, I have to use a type assertion for the variable 'day' to avoid any errors. I don't simply do const day: Day = 2 because the value I receive is a string (dynamic value), and a type assertion is necessary ...

Dividing a JSON object into arrays containing keys and values within an Angular framework

I have a code snippet that involves receiving a JSON object of type Tenant from an API. I need to separate this object into keys and values within my function called tenantParser(). However, when I try to log displayedValues and displayedKeys, both show ...

What is the best way for a parent process to interrupt a child_process using a command?

I'm currently in the process of working on a project that involves having the user click on an 'execute' button to trigger a child_process running in the backend to handle a time-consuming task. The code snippet for this operation is shown b ...

What is the proper way to implement jest.mock in a describe or it block?

Using typescript and jest, I am faced with a scenario involving two files: users.service.ts, which imports producer.ts. In an attempt to mock a function in producer.ts, I successfully implement it. import { sendUserData } from "./users.service"; const pro ...

Creating a Redis client in Typescript using the `redis.createClient()` function

I'm currently trying to integrate Redis (v4.0.1) into my Express server using TypeScript, but I've encountered a small issue. As I am still in the process of learning TypeScript, I keep getting red underline errors on the host parameter within th ...

Guide for adjusting icon dimensions in Material-UI breakpoints

import { Container } from "@mui/material"; import * as React from "react"; import { Home } from "@mui/icons-material"; import PersonIcon from "@mui/icons-material/Person"; import FormatListBulletedIcon from "@mu ...

Can we guarantee that the key and its corresponding value are both identical strings in Typescript?

Is it possible to enforce the key of a Record to be the same as the inner name value in a large dataset? interface Person<T> { name: T title: string description: string } type People = Record<string, Person<string>> // example dat ...

Angular - Implementing validation for maximum character length in ngx-intl-tel-input

Utilizing the ngx-intl-tel-input package in my Angular-12 project multistep has been quite promising. Below is a snippet of the code: Component: import { SearchCountryField, CountryISO, PhoneNumberFormat } from 'ngx-intl-tel-input'; expor ...

Steps for setting up the 'node_modules' folder in an older Angular project using the 'npm install' command

Currently, I am in the process of transferring our project code from our repository to a new laptop. The project was initially developed on Angular 5 last year. However, the new laptop is equipped with the latest versions of Angular CLI, NodeJS, and NPM to ...

Angular - applying a class to a component's selector

Currently, I am utilizing the router module to showcase my components. Previously, in the root section, I included <app-catalog class="column is-3"></app-catalog> Now, with the router implementation, my setup includes <router-outlet>&l ...