How to transfer a parameter in Angular 2

I am currently facing a challenge in passing a value from the HTML file to my component and then incorporating it into my JSON feed URL.

While I have successfully transferred the value to the component and displayed it in the HTML file, I am struggling to append it to the end of my JSON feed URL.

It's worth noting that both the component and HTML file are generated directly from Angular 2 CLI.

app.component.ts

import { Component } from '@angular/core';
import {Http} from '@angular/http';
import {HTTP_PROVIDERS} from '@angular/http';

@Component({
  moduleId: module.id,
  selector: 'app-root',
  templateUrl: 'app.component.html',
  styleUrls: ['app.component.css']
})
export class AppComponent {
  title = 'app works!';

  values = '';
   onKey(value: string) {
    this.values = value + ''; // pass this value to the URL below
  }

    people: Array<Object>;
    constructor(http: Http) {
        http.get('http://myurl.com/json_feed.php?q=' + this.values) // retrieve the value from above
        .subscribe(res => {
        this.people = res.json();
      })
    }
}

app.component.html

<h1>
  {{title}}
</h1>

<input #box (keyup)="onKey(box.value)">

{{values}}

<ul *ngFor="let person of people">
  <li class="text">
    {{person.model}}
  </li>
</ul>

Answer №1

The method used to add a value to the stream in the current code is incorrect. this.values = value + '';

Instead of appending the new value to the existing values, it is simply replacing them each time. The correct code should be

this.values = this.values + value + '';

Answer №2

In the wise words of Günter Zöchbauer, the constructor in a component is executed during its creation and cannot be used to update values. To achieve this, you need to follow a similar approach:

export class AppComponent {

  ...

  values = '';

  onKey(value: string) {

    this.values += value + '';

    getData(); // invoke getData method
  }

  people: Array<Object>;

  constructor(public http: Http) {

  }

  getData(){

      this.http.get('http://myurl.com/json_feed.php?q=' + this.values)
      ...

    })
  }

}

It's important to remember that your HTTP request will fail if you forget to include HTTP_PROVIDERS when bootstrapping the application in your main.ts.

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 way to display the output of a Set-typed function using a class key in my code?

I'm currently working on developing a function that can return a Set containing the keys of a class. However, I am struggling to determine the correct definition for this function. class Bot { public no01: number; public no02: number; construct ...

UI not reflecting updated form validation after changes made

Currently, I have a situation where I am passing a form from the Parent component to the Child component. All the validations are being handled in the Parent component and the Child component is simply rendering it. However, there is a specific field calle ...

Organizing, storing, and arranging data within a struct in Angular

I have a JSON file containing a lot of information that can be sorted in various ways. The specific JSON data is too lengthy to include here, but for illustrative purposes, it may look something like this: $myData = { "id":1, "author_id":[17], "dat ...

How to retrieve a specific set of keys in a Python dictionary

I received this object from the Telegram API: {'ok': True, 'result': [{'update_id': 634527149, 'message': {'message_id': 2, 'from': {'id': 5060166011, 'is_bot': False, 'fi ...

Assign the value from JavaScript to the element with the "ng required" attribute, without resetting frm.$error.required to false

My situation involves using a button with ng-style that relies on frm.mybtn.$error.required as follows: ng-style="frm.mybtn.$error.required?{'border-color':'#a94442'}:''" I am updating the value of the button from JavaScript ...

Arrange a JSON file by organizing a key located within an array of dictionaries using Python

Here's a structure that I am working with: [{ "name": "apple", "price": "5.0", "record": [ { "id": "008", "time": 1465689600 } ] },{ "name": "banana", "price": "9.0", "record": [ ...

Mastering the Angular 4.3 HttpClient: Maximizing the Potential of HttpHeaders and Interceptor

I'm having trouble sending headers to my HttpRequest. I have searched extensively and tried several solutions that I found, but none of them seem to be working. When inspecting the clonedRequest object, it seems that the headers are not being sent t ...

Adjusting the date format in Angular Material date picker dynamically

I am facing a challenge with my angular material date picker. I have set the default date format to dd/mm/yyyy for the entire app, but in certain instances, I need it to display as dd/mm/yy instead. Instead of creating a new date picker component just for ...

Attempting to simulate the behavior of Angular2 Token during testing

Currently, I am working on obtaining a token that is required for API authentication to retrieve a list. My approach begins with importing the angular2-token library: import { Angular2TokenService } from 'angular2-token'; After this, I include ...

What are the best options for implementing models and controllers in Facebook's React library using ES6?

As someone who is new to the react/es6 stack and framework, I'm transitioning from developing in Backbone/Marionette.js. I've been exploring ES6 and React more recently and, coming from a background where I'm used to Backbone for Model and C ...

What is the best way to programmatically generate a service within Angular?

Is there a way to dynamically create services at runtime using a string name (like reflection)? For example: let myService = new window[myClassName](myParams); Alternatively, you could try: let myService = Object.create(window[myClassName].prototype); m ...

Error in Android Studio Gradle: Project_info object is not found

Revisiting this question because the answer is no longer applicable, with the link now leading to Firebase: Gradle fails building with "Missing project_info object" I am trying to add the google-services.json file to my Android Studio project. ...

The attribute 'name' cannot be found within the class 'MyComponent'

I'm a beginner in Angular2 and I have no previous knowledge of version 1. Can you help me understand why this error is occurring and guide me on how to fix it? import { Component } from 'angular2/core'; @Component ({ selector: 'my- ...

Angular Universal experiences issues with route functionality after page reloads

Recently deployed an Angular Universal web app on Firebase. While all routes within the application are functioning properly, encountering errors when trying to access them externally. Below is the error message: functions: Starting execution of "ssr" ⚠ ...

Ng-repeat loop: Checkbox checked when two values are matched

Is there a way to automatically check a checkbox within an ng-repeat if two specific values are true? For instance: <div ng-repeat="item in list"> <input type="checkbox" ng-checked="((item.value1 == true) + (item.value2 == true))" /> < ...

Combining Angular Scripts with Model-View-Controller

For my shell page "index.html," I am required to include all the necessary files such as js, css, etc. Example : <!-- Third party libraries --> <script type="text/javascript" src="scripts/angular.min.js"></script> <script type="text/ ...

The API request does not provide randomized results and does not show any display

I am facing an issue with a button that is supposed to fetch a random user from an API. When I retrieve all the users, the information is displayed correctly. However, when I try to select a user at random, it does not work as expected. Also, it seems to a ...

Exploring Ruby's hash and array features

Within my Rails application, I am tasked with sending a complex JSON string that requires decoding. While this is not an issue, I want to access sample JSON structures beforehand to ensure I can navigate through all the variables. The challenge lies in the ...

The necessary directive controller is missing from the element in the current DOM structure

Can anyone explain the meaning of "required directive controller is not present on the current DOM element"? I encountered this error and would like some clarity. For reference, here is the link to the error: https://docs.angularjs.org/error/$compile/ctr ...

Ensure that the background view remains interactive while adding an overlay on top for an enhanced user experience

Hey everyone, I could use some help with a question I have. My issue is that I am struggling to figure out how to make two views overlap while still allowing the background view to be interactive. Currently, I am using absolute positioning for the foregr ...