Methods in Ionic to call an external JavaScript file from TypeScript

Having a JSON list stored in a JavaScript file, my objective is to filter it using TypeScript before sending the filtered results to the HTML homepage. However, I encountered an issue within the HTML file.

It's worth mentioning that when running the code in an online TypeScript editor, everything worked smoothly.

The JavaScript file, list.js, holds the following data:

var jsonList= [
  {
    "Answer": "Y",
    dummyProp1 : 1
  },
  {
    "Answer": "N",
    dummyProp1 : 1
  }
];

Moving on to the TypeScript file, home.ts:

import { Component,OnInit } from '@angular/core';
import 'src/assets/list.js';

declare var list:any[];
declare var jsonlist:any[];

@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss'],
})
export class HomePage implements OnInit {

constructor() {
}

ngOnInit() {
function filterJson() {
return this.list.filter(e => (
(e.Answer.indexOf('Y') === 0) 
))
}

var o = filterJson();

for(var key in o) {
var infoJSON = o[key];
jsonlist.push(infoJSON.Answer)
}

console.log(jsonlist);
}
}

This is what the home index file looks like:

<body>
  <app-root></app-root>
  <script type="text/javascript" src="src/assets/list.js"></script>
</body>

Finally, here's the content of the home page file, home.html:

<div *ngFor="let item of jsonlist">
  <ion-item>
    <ion-label><b>{{item}}</b></ion-label>
  </ion-item>
</div>

<p>An error message was displayed as follows:</p>
<blockquote>
Property 'jsonlist' does not exist on type 'HomePage'. ngtsc(2339) home.page.ts(11, 49): Error occurs in the template of component HomePage.
</blockquote>
</div></questionbody>
<exquestionbody>
<div class="question">
                
<p>While working with a JSON list in a JavaScript file and wanting to implement filtering in TypeScript before displaying the results on the HTML homepage, an error occurred within the HTML file.</p>
<p>Note: The code executed flawlessly in an online TypeScript editor.</p>
<p>The contents of the JavaScript file, list.js, are as follows:</p>
<pre><code>var jsonList= [
  {
    "Answer": "Y",
    dummyProp1 : 1
  },
{
    "Answer": "N",
    dummyProp1 : 1
  }];

As for the TypeScript file, home.ts:

import { Component,OnInit } from '@angular/core';
import 'src/assets/list.js';

declare var list:any[];
declare var jsonlist:any[];

@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss'],
})
export class HomePage implements OnInit {

  constructor() {
  }
//extract only yes answers

ngOnInit() {
  function filterJson() {
    return this.list.filter(e => (
      (e.Answer.indexOf('Y') === 0) 
    ))
  }

  var o = filterJson();

  //get only Answers
  
  for(var key in o) {
    var infoJSON = o[key];
    jsonlist.push(infoJSON.Answer)
  }
  
  console.log(jsonlist);
}
}

The structure of the home index file:

<body>
  <app-root></app-root>
  <script type="text/javascript" src="src/assets/list.js"></script>
</body>

Content of the home page file, home.html:

<div *ngFor="let item of jsonlist">
<ion-item>
  <ion-label><b>{{item}}</b></ion-label>
  </ion-item>

Error Message: Property 'jsonlist' does not exist on type 'HomePage'. ngtsc(2339) home.page.ts(11, 49): Error occurs in the template of component HomePage.

Answer №1

The json file you provided is not valid according to the json format standards. Instead of defining variables within a json file, you should only define your data in json format.

Here's an example of a valid json:

[
  {
    "Answer": "Yes",
    "dummyProp1" : 1
   },
   {
    "Answer": "No",
    "dummyProp1" : 1
   }
]

In TypeScript, declaring means creating a declaration for an unknown reference that can be used to assist in building. However, you cannot access these declarations as variables.

When working with an Angular template, you should only access properties defined in the component class. It is not recommended (and likely not possible) to access variables outside of the component class.

A better approach would be to use TypeScript instead of JSON.

If your JSON value does not need to change after the build process is completed, you can create it as a .ts file and export the JSON array from there.

For example, create a file named mydata.ts:

export default [
  {
    Answer: "Yes",
    dummyProp1: 1,
  },
  {
    Answer: "No",
    dummyProp1: 1,
  },
];

In your Angular component, you can import the myData variable and assign it to your property.

import myData from "./mydata";

export class HomePage { 

  dataList: Array<{ Answer: string; dummyProp1: number }>;
  
  ngOnInit() {
    this.dataList = myData;
    // You can perform all your operations, binding, filtering, etc. using the dataList property
  }
}

If you must use a .json file, you can refer to this answer on how to import it and assign the imported value to a component property.

However, if you need to modify the JSON file after building or if you intend to serve the file from a server (using a deployment tool or similar), you will need to use HttpClientModule or another tool to retrieve data through HTTP/WebSocket requests.

For more information on how to use HttpClientModule, you can refer to this blog post.

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

Assign variable data to properties within an immutable object within a React component

I have declared a Const in my config.service.ts file like this: export const mysettings={ userid:"12324", conf:{ sessionDuration:30, mac:"LON124" } } I am using this constant in various components. However, instead of hardcoding these val ...

Changing the order of a list in TypeScript according to a property called 'rank'

I am currently working on a function to rearrange a list based on their rank property. Let's consider the following example: (my object also contains other properties) var array=[ {id:1,rank:2}, {id:18,rank:1}, {id:53,rank:3}, {id:3,rank:5}, {id:19,r ...

Developing a node module that includes nested subfolders

I'm currently working on an npm module and have the following index.ts file: export * from './src/A/index'; Right now, when importing in my app, it looks like this: import {something} from 'myModule'; Now, I want to enhance my ...

Routing with nested modules in Angular 2 can be achieved by using the same

Encountering a common issue within a backend application. Various resources can be accessed through the following routes: reports/view/:id campains/view/:id suts/view/:id certifications/view/:id Note that all routes end with the same part: /view/:id. ...

Monitoring internet navigation with Angular

I'm struggling to figure out how I can access the browsing history in Angular. In AngularJS, $location provided some functionality related to this, but in Angular, the Location service only offers forward and back methods without a way to view the ful ...

Navigating TS errors when dealing with child components in Vue and Typescript

Recently, I encountered an issue where I created a custom class-based Vue component and wanted to access its methods and computed properties from a parent component. I found an example in the Vue Docs that seemed to address my problem (https://v2.vuejs.org ...

The compilation of the module has encountered an error with the PostCSS loader. There is a SyntaxError at line 2, character 14 indicating an unknown

I am developing an Angular 8 application. Currently, I am incorporating AlertifyJs into my project. In the styles.css file of Angular, I have imported these libraries: @import '../node_modules/alertifyjs/build/alertify.min.js'; @import '. ...

What is the best way to host a single page application within a sub-directory using nginx?

Trying to set up nginx to host an Angular application from a unique child path. Adjusted the app to use a base href of fish, able to serve root page and assets correctly. However, encountering a 404 error when attempting to reload the page on a child rout ...

Title remains consistent | Angular 4

Struggling to change the document title on a specific route. The route is initially set with a default title. { path: 'artikel/:id/:slug', component: ArticleComponent, data: {title: 'Article', routeType: RouteType.ARTICLE, des ...

How can a button click function be triggered in another component?

These are the three components in my dashboard.html <top-nav></top-nav> <sidebar-cmp></sidebar-cmp> <section class="main-container" [ngClass]="{sidebarPushRight: isActive}"> <router-outlet></router-outlet> & ...

The function res.status is not defined

Currently, I am in the process of integrating my upcoming app with Google Sheets. I have relocated the function that manages the post request to "app/api/sheets" as per the recommended documentation. import type { NextApiRequest, NextApiResponse } from &ap ...

Instructions on how to implement a readmore button for texts that exceed a specific character length

I am attempting to display a "Read more" button if the length of a comment exceeds 80 characters. This is how I am checking it: <tr repeat.for="m of comments"> <td if.bind="showLess">${m.comment.length < 80 ? m.comment : ...

choosing between different options within Angular reactive forms

I am attempting to create a select element with one option for each item in my classes array. Here is the TypeScript file: @Component({ selector: 'app-create-deck', templateUrl: './create-deck.component.html', styleUrls: [' ...

The new data is not being fetched before *ngFor is updating

In the process of developing a "Meeting List" feature that allows users to create new meetings and join existing ones. My technology stack includes: FrontEnd: Angular API: Firebase Cloud Functions DB: Firebase realtime DB To display the list of meeting ...

Finding out whether the current date falls between a startDate and endDate within a nested object in mongoose can be done by using a specific method

My data structure includes a nested object as shown: votingPeriod: {startDate: ISOdate(), endDate: ISOdate()}. Despite using the query below, I am getting an empty object back from my MongoDB. const organizations = await this.organizationRepository.find( ...

Forwarding refs in React FC allows you to easily pass down

I have encountered an issue with references - I am trying to reference a function component and pass props to it. Currently, I have my Parent component and Child Component set up. In the parent component, I need to use a ref to access my child component. S ...

Substitute all attributes of objects with a different designation

I need to update all object properties from label to text. Given: [ { "value": "45a8", "label": "45A8", "children": [ { "value": "45a8.ba08", "label": "BA08", &q ...

The process of releasing a component created with angular-starter onto npm is now underway

After creating angular components with the Angular Starter Kit from https://github.com/AngularClass/angular-starter, I am looking to package them and deploy them on NPM for easy use in other projects. However, I found the documentation to be lacking in thi ...

Exploring the integration of external javascript AMD Modules within Angular2 CLI

During my experience with Angular2 pre-releases, I found myself using systemjs to incorporate external JavaScript libraries like the ESRI ArcGIS JavaScript API, which operates on AMD modules (although typings are available). Now that I am looking to trans ...

Exploring the various form types supported by 'react-hook-form'

I utilized react hooks form to create this form: import React from "react"; import ReactDOM from "react-dom"; import { useForm, SubmitHandler } from "react-hook-form"; import "./styles.css"; function App() { type ...