An error has occurred while processing the "click" function

Embarking on my journey to create Angular2 with TypeScript for the first time and seeking guidance. The initial request is functioning correctly and I am able to display it. Upon clicking, I wish to initiate a new request. How can this be achieved?


export class App {
  img: Array<Object>;
  constructor(http:Http) {    
    http.request('http://boroviha.dev.ooosis.com/api/client/get_photo_sections.php').toRx().subscribe(res => {
      console.log('img', res.json().data);
      this.img = res.json().data;
    });
  }
  
  onSelect(item: img) { 
    this.selectedItem = item; 
    console.log(item);     
    constructor(http:Http) {
      this.http.request('http://localhost:3001/api/random-quote')
        .map(res => res.text())
        .subscribe(
          data => this.randomQuote = data,
          err => this.logError(err),
          () => console.log('Random Quote Complete')
        );
     }
  }
}

bootstrap(App, [HTTP_BINDINGS, bind(RequestOptions).toClass(MyOptions)])
  .catch(err => console.error(err));

Answer №1

Your implementation involves defining a constructor within the onSelect method, which is unconventional:

onSelect(item: img) { this.selectedItem = item; console.log(item);
  constructor(http:Http) {
  (...)

A more structured approach would look something like this:

export class App {
  img: Array<Object>;
  constructor(private http:Http) {    
    (...)
  }

  onSelect(item: img) {
    this.selectedItem = item;
    console.log(item);
    this.http.get('http://localhost:3001/api/random-quote')
        .map(res => res.text())
        .subscribe(
          data => this.randomQuote = data,
          err => this.logError(err),
          () => console.log('Random Quote Complete')
        );
    }
  }
}

I have made sure to include private in the constructor parameters to integrate the http parameter into the App class for ease of use with the this keyword.

It's worth noting that you should now use HTTP_PROVIDERS instead of HTTP_BINDINGS.

Trust this modification proves beneficial to you, Thierry

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

Use the constant INLINE with npm commands to specify inline behavior

Today I was working on Angular2 using the template provided at . Following the installation guide, I executed the commands as instructed. I have successfully installed Node.js v6.9.1. npm install --Executed without any issues. npm server --Encountered a ...

Encountered an unhandled exception: Module 'source-map' not found while attempting to run Angular on a Raspberry Pi

I am currently developing an Angular application to run on a Raspberry Pi. However, I encountered the following error when trying to start the application: An unhandled exception occurred: Cannot find module 'source-map' Require stack: - /home/pi ...

Why isn't $stateChangeStart triggered when the state changes in UI-Router with ES6?

Currently, I am utilizing Bable for ES6 and webpack while working on an angular 1.x.x application. So far, I haven't encountered any issues. I am looking to implement a feature where I can keep track of all the Route Changes using UI-Router. However, ...

When using TypeScript, it is important to ensure that the type of the Get and Set accessors for properties returning a

Why is it necessary for TypeScript to require Get/Set accessors to have the same type? For example, if we want a property that returns a promise. module App { export interface MyInterface { foo: ng.IPromise<IStuff>; } export int ...

Error: Unable to access the 'DASH' property as it is undefined

Within my current project, I aim to showcase data related to cryptocurrencies. After making an API call, I successfully obtained a response. The specifications of my environment are as follows: Node: 8.9.5, Express: 4.16.4, Angular CLI: 7.3.6, Typescript ...

Tips for monitoring dispatch in fetch/middleware functions

Just testing a basic webpage <template> <HomeTemplate /> </template> <script lang="ts"> import Vue from 'vue' export default Vue.extend({ async fetch(context) { // or middleware(context) await context.store.disp ...

The Access-Control-Allow-Headers does not permit the use of the Authentication request header field

I've noticed this question frequently popping up on Stack Overflow without a clear explanation of its significance. Could someone kindly elaborate on the meaning of this error? Request header field Authentication is not allowed by Access-Control-Allo ...

Live server code does not update with changes made in Angular

https://i.stack.imgur.com/Yo6Y8.png In the screenshot above, you can see my changes. I simply modified the text to read Download PDF, replacing what was there previously. Instead of the folder shown here, I used the code from this compiled file: https:// ...

Retrieving User's Theme Preference from Local Storage in Next.js Instantly

As mentioned in various other responses, such as this one, Next.js operates on both the client and server side, requiring a guard to properly fetch from localStorage: if (typeof localStorage !== "undefined") { return localStorage.getItem("theme") } else ...

Tips for resolving SyntaxError: Unable to utilize import when integrating Magic with NextJS in a Typescript configuration

Looking to integrate Magic into NextJS using TypeScript. Following a guide that uses JavaScript instead of TypeScript: https://github.com/magiclabs/example-nextjs Encountering an issue when trying to import Magic as shown below: import { Magic } from &qu ...

A guide on toggling a div in Ionic3

Looking to improve user experience, I need to display a long text partially with an 'expand' button. Clicking the button will reveal the full text. User interface design: Default view: https://i.sstatic.net/whJDN.png After expansion: https:/ ...

Implement a Telerik SideDrawer component in every single view of your application

After successfully implementing the Telerik Side-drawer in a single view, my next challenge is making it accessible globally as a reusable component. I want to find a way to avoid manually copying and pasting the code into every view. So, my question is: ...

The ListBuckets command in AWS S3 provides a comprehensive list of all available

I'm currently working on a TypeScript application that interacts with an AWS S3 bucket. The issue I'm facing is that my current credentials only allow me to read and write data to specific buckets, not all of them. For example: ListBuckets retu ...

What is the best way to retrieve a soft deleted entity from typeorm in a postgreSQL database?

Can anyone help me figure out how to retrieve soft deleted documents from a PostgreSQL database using TypeORM's find, findOne, or query builder get/getMany methods? I keep getting undefined as the result. Is there a way to access these deleted values? ...

What is the best way to handle resolving a promise nested within another promise and retrieving the result within a controller?

I have a situation where I need to modify the result of a promise returned by a function in one service and make this altered value accessible to my controllers from another service. angular.module('test').service("service1", function($q) { ...

What strategies should be employed to develop an Angular 4 application seamlessly integrated with Asp.NET Core?

I attempted to test out a couple of templates which turned out to be unsuccessful: https://github.com/asadsahi/AspNetCoreSpa https://github.com/MarkPieszak/aspnetcore-angular2-universal Unfortunately, neither of them worked properly for me. I'm cu ...

The mysterious HTML element "modal" within Angular2

I am looking to create a custom modal window by following the instructions in this link:- However, when I try using it, I encounter an issue where it shows an unknown HTML tag error in the console. The error message reads: Unhandled Promise rejection: Te ...

Challenges with slow performance in Ionic application when handling extensive amounts of data

We're facing performance issues with our ionic angular contact management app. The app experiences severe slowdown as the number of contacts increases, affecting taps, scrolls, and overall responsiveness. Despite utilizing offline storage to store da ...

Keep clicking on the Protractor element until it becomes enabled

I am facing an issue while trying to write a test where my results are displayed on multiple pages. I can navigate to the next page by clicking a button, but if the button is disabled, I need to handle that scenario. How can I achieve this with Protractor? ...

Error: The JSON file cannot be located by the @rollup/plugin-typescript plugin

I have recently set up a Svelte project and decided to leverage JSON files for the Svelte i18n package. However, I am facing challenges when trying to import a JSON file. Although the necessary package is installed, I can't figure out why the Typescri ...