How to Pass a JSON Object to a Child Component in Angular and Display It Without Showing "[Object

Need help with my API call implementation. Here's a snippet from my Input component:

Input.html

<form (submit)="getTransactions()">
  <div class="form-group">
    <label for="exampleInputEmail1"></label>
    <input type="text" class="form-control"  [(ngModel)]="address" name="address" placeholder="Bitcoin Address">
    <button type="submit" class="btn btn-primary">Submit</button>
    {{address}}
  </div>
</form>

<app-display [address]="transactions"></app-display>

input.ts

export class InputComponent implements OnInit {

  address = "3MvuMn4CESuvA89bfA1cT8mgC4JtKaReku";
  transactions = [];

  constructor(private blockchain: BlockchainService) { }

  ngOnInit() {
  }

  submit(){
    console.log(this.address)
  }

  getTransactions(){
    this.blockchain.getTransactions().subscribe((data) => {
      // console.log(data.json())
      this.transactions = data.json();
      console.log(this.transactions)
    });
  }

}

Console logging shows the json object correctly in my Input component, but in my Display component I'm getting "[object Object]". No errors are thrown.

display.htlm

<button (click)="hello()"></button>

display.ts

export class DisplayComponent implements OnInit {

  @Input() address = [];

  constructor(private blockchain: BlockchainService) { }

  ngOnInit() {
  }

  hello(){
    console.log(`data ${this.address}`);
  }

}

service.ts

@Injectable()
export class BlockchainService {

  baseurl: string = "http://localhost:4200/assets/info.json"

  constructor(private http: Http) { }

  getTransactions(){
    return this.http.get(this.baseurl);
  }

}

Answer №1

Here is some code that could be useful for you:

this.blockchain.getTransactions().subscribe(
    (data => {
        if (data['status'] == 200) {
            this.transactions = JSON.parse(data["_body"]);
        }
    }),
    error => this.toastr.error('Something went wrong !!', 'Oops!',{showCloseButton: true})
);

Alternatively, you can modify this in your service:


return this._http.get("your path").map(data => data.json())

this.blockchain.getTransactions().subscribe(
    (data => {
        if (data) {
            this.transactions = data;
        }
    }),
    error => this.toastr.error('Something went wrong !!', 'Oops!',{showCloseButton: true})
);

Answer №2

To properly access the data from the JSON object (address), ensure that you parse it in your DisplayComponent.

export class DisplayComponent implements OnInit {

  @Input() address: any;

  constructor(private blockchain: BlockchainService) { }

  ngOnInit() {
this.address  = JSON.parse(this.address);
  }

  hello(){
    console.log(`data ${this.address}`);
  }

}

It is important to note that you should use the .json() method in your Input component.

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

Is it necessary to list all potential strings for accessibilityRole?

When working with accessibilityRole in React Native, I am wondering if there is a way to import all the possible strings instead of typing them out manually. createAccessibilityRole(parent: Element): string { if(isLink) return 'link' return ...

Variations of a particular software package are necessary

My current project requires Expo, React, and React-Native as dependencies. The configuration in the package.jason file looks like this: "main": "node_modules/expo/AppEntry.js", "private": true, "dependencies": { "expo": "^28.0.0", "expo-three": "^ ...

Having trouble uploading an image using Dropzone.js in conjunction with Node.js? Let us assist you with that!

Currently working on developing a web application using Express and Node.js. I am looking to enable users to upload profile pictures utilizing Dropzone.js. Here is what I have implemented so far: <script type="text/javascript"> Dropzone.options. ...

Adding a backslash in Angular: Tips and Tricks

I have a question about adding a backslash to a string that is returned from a div, for example Car1 \sold. Although I am able to retrieve the status, I am having trouble adding the backslash. Here is what I have tried so far: <span>{{addBackl ...

Leveraging Express for handling GET requests within a server

Below are two predefined and hard coded GET requests to fetch JSON data from the server. Is it possible to combine these two GET requests into one, generating JSON dynamically with just a single request? The output should depend on the input received from ...

Guidelines for creating a binary release of Node.js with native modules

Currently, I am in the midst of exploring the world of Node.js projects, delving into different bundlers and various other components. One interesting concept that came to mind is the idea of bundling Node.js into a single binary for Linux, macOS, or Windo ...

Fastify endpoint failing to respond to designated URL

Within my code, there is a router setup: fastify.get('/:link', (req, reply) => { req.params.url = req.host+req.url; reply.view("template.ejs",req.params); }); I am trying to capture URLs and process them in the template. All URLs are ...

Weighing the importance of a multiple-choice quiz

I am faced with the challenge of assessing 25 multiple choice questions, each offering 4 answer choices worth varying points. Additionally, I have 2 free response questions that I wish to score based on the time taken to answer them. My proposed scoring ru ...

What are some effective methods for troubleshooting unidentified JavaScript functions within Chrome's performance analyzer?

Currently, I am utilizing Angular 4 and incorporating numerous anonymous arrow functions (() => {}). I am curious if it is feasible to identify these functions in Chrome's performance analyzer without assigning them names. Below is an example of t ...

In Node JS, the variable ID is unable to be accessed outside of the Mongoose

When working with a Mongoose query, I encountered an error where I am trying to assign two different values to the same variable based on the query result. However, I keep getting this error: events.js:187 throw er; // Unhandled 'error' ev ...

Issues with Semantic UI Calendar not displaying properly

I am currently experimenting with the Semantic UI Calendar, where there is a date input field and a calendar that pops up when selected as demonstrated in this initial example. Since I am not familiar with this process, I am uncertain if I have properly li ...

Document: include checksum in HTML

I have a set of three files. The file named loader.js is responsible for creating an iframe that loads another file called content.html, which in turn loads content.js. I have made loader.js publicly available so that other users can include it on their ow ...

Personalized error management within Express.js

This helpful resource explains the process of custom error handling in Express.js using the following code snippet: app.use(function(err, req, res, next) { // Here you can perform logging and display user-friendly error messages console.error(err); res.st ...

Can we limit the return type of arrow function parameters in TypeScript?

Within my typescript code, there is a function that takes in two parameters: a configuration object and a function: function executeMaybe<Input, Output> ( config: { percent: number }, fn: (i: Input) => Output ): (i: Input) => Output | &apos ...

Is there a way to utilize a value from one column within a Datatables constructor for another column's operation?

In my Typescript constructor, I am working on constructing a datatable with properties like 'orderable', 'data' and 'name'. One thing I'm trying to figure out is how to control the visibility of one column based on the va ...

Limiting the parameter type in Node.js and TypeScript functions

Currently working on a Node.js project utilizing TypeScript. I'm attempting to limit the argument type of a function to a specific base class. As a newcomer to both Node and TypeScript with a background in C#, I may not fully grasp some of the langua ...

How can one click the button within the expanded dropdown while hovering over the navigation item in Angular and Bootstrap?

Issue Description: Upon hovering over a navigation item, the dropdown container is displayed but it's not clickable. Desired Behavior: Hovering over a navigation item should display the dropdown container and allow clicking on its contents. Furthermo ...

Typescript has a knack for uncovering non-existent errors

When I attempted to perform a save operation in MongoDB using Mongoose, the code I initially tried was not functioning as expected. Upon conducting a search online, I came across a solution that worked successfully; however, TypeScript continued to flag an ...

The server appears to be up and running, however there seems to be an issue when attempting to access the API as it is returning an Error: connect ECONNREFUSED 127.0.0.1

Trying to decouple app and server. Successfully running, but encountering Error: connect ECONNREFUSED 127.0.0.1:3000 in Postman when hitting "app.get('/')" API despite making necessary changes. In ./routes/users.js const express = requ ...

Tips for closing print window dialog during Protractor testing

Currently, I am performing end-to-end testing using protractor. During a specific test, I need to verify if the print button is successfully creating a PDF. When the test clicks on the button, it triggers a print window dialog as shown below: https://i.st ...