Transferring API Response (object) Parsing between Components in Angular 4

I need to transfer API response to another component

The following code is from 'detail_item.component.ts', where data is sent to the route "bookitem" in 'book_item.component.ts'

onSubmit(){
    this.appService.addItem(this.item).subscribe(item => {
      if(item.status ==200){
        this.router.navigate(['/bookitem'], {queryParams: {data: item.data}});
      }
    })
}

This code snippet is from 'book_item.component.ts'

ngOnInit() {
    this.routeActive.queryParams.filter(params => params.data).subscribe(params => {
       this.book_item = params.data;
    });
}

After using console.log(this.book_item), the output is [object object] instead of expected JSON data.

Answer №1

When dealing with an object type in item.data, it is important to first convert it to a string as shown below:

onSubmit(){
    this.appService.addItem(this.item).subscribe(item => {
      if(item.status ==200){
        this.router.navigate(['/bookitem'], {queryParams: {data: 
JSON.stringify(item.data)}});
      }
    })
}

Then, you will be able to parse it when retrieving it from the route in another component:

 ngOnInit() {
     this.book_item = JSON.parse(this.route.snapshot.queryParams['data']);
          }

Answer №2

You received the result [object object]. This is acceptable since you are attempting to include an object in the query string. However, it is important to note that objects cannot be directly passed in a query string. Instead, values that can easily be converted to strings, such as numbers, should be used.

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

Activate the ion-navbar button when submitting from the modal page

import { Component } from '@angular/core'; import { NavController, NavParams } from 'ionic-angular'; import {ModalPage} from '../modal-page/modal-page'; @Component({ selector: 'page-page2', templateUrl: 'pa ...

Creating an object with mapped properties from enumeration values using Typescript

I am trying to find a way to automatically create an object with values computed during compilation using enumeration values and pre-defined function calls. The basic concept is to associate certain arguments of a function with keys. For example, consider ...

What is the reasoning behind TypeScript's acceptance of value as a data type?

What is the reason for TypeScript supporting value as a data type? The following scenarios demonstrate both acceptable and unacceptable declarations. export class MyComponent{ error: 'test' = 'test'; // accept error: & ...

Tips for validating the upload functionality of a .csv file using Protractor

I'm currently testing the upload functionality of a csv file in protractor. Below is the code I am using: const absPath = path.resolve(__dirname, 'csvFile.csv'); const fileInput = element(by.css('input[type=file]')); browser.wait ...

Is it possible to render dynamic components based on the input property of the parent?

Essentially, I have a top-level component called "Pageview" that showcases various instances of a specific component being utilized. The component being displayed can be changed by providing a route input property to the Pageview component. My goal is to s ...

Please delineate an unfinished Record, ensuring the constraints on the assigned type are maintained

Imagine having an interface S: interface S { a: string; b: number; c: string; } The goal is to establish an incomplete mapping from S to another type called AllowedMappedType: type AllowedMappedType = "red" | "green" | "blue ...

Is it correct to implement an interface with a constructor in TypeScript using this method?

I am completely new to TypeScript (and JavaScript for the most part). I recently came across the article discussing the differences between the static and instance sides of classes in the TypeScript handbook. It suggested separating the constructor into an ...

How can I retrieve query parameters passed from an Angular application in PHP?

I'm trying to figure out how to retrieve data from query parameters sent by an Angular application in PHP. Unfortunately, I don't have much experience with PHP. Is there anyone willing to lend a hand? ...

Discovering how to properly run tests on a function within an if statement using Jasmin, Karma

I've recently started unit testing and I'm facing an issue with my component. The component calls a service to display a list of students. getListStudents() { this.noteService.getStudents({}).subscribe(res => { this.students= res })} Then ...

Utilizing Object.keys in Typescript to loop through a key-value pair collection

After creating an interface for my dictionary and initializing it, I encountered an unexpected output when trying to print the keys. export interface IHash { [tagName: string] : string; } var x : IHash = {}; x["first"] = "details"; x["second"] = "det ...

What is the best way to parse JSON data with Typescript?

I am dealing with JSON data structured as follows: jsonList= [ {name:'chennai', code:'maa'} {name:'delhi', code:'del'} .... .... .... {name:'salem', code:'che'} {name:'bengaluru' ...

Struggling to create an Extension Method for Map<TKey, TValue[]> in TypeScript

As a new Angular/TypeScript user, I am really enjoying using Extension methods. They work well on standard types, but now I am facing an issue while trying to write one for the Map data structure where values are arrays. Unfortunately, it does not seem to ...

transmit information to a service using Angular 8

There are 4 multiselect dropdowns, and when I click on an event, I save the data array of objects in the same component. Now, I need to send this data to display it in another component. To achieve this, I am using a service. However, every time I send th ...

Struggling to Add an Item to a Fixed List Linked to Grid

I am attempting to add a placeholder value to an Immutable list that is linked to a Grid component. However, upon inspection, the added value does not seem to be visible. private filterdSchoolSelectionData: Immutable.List<SchoolSelectionListData> = I ...

An issue has occurred: Failure to execute spawnSync PATH/target/node/node ENOENTNGCC. Please refer to the

Attempting to initiate my angular project using ./mvnw is resulting in an error when the build runs ng build --configuration development. The error message thrown reads as follows: Generating browser application bundles (phase: setup)... [INFO] /home/use ...

Is it possible for pdfjs-dist to be used with Typescript?

Is there a way to preview a PDF as a canvas without importing pdfjs-dist into my project? I have already used the command $yarn add pdfjs-dist to install pdfjs-dist. Do I need to include any additional imports? import pdfjsLib from "pdfjs-dist/build ...

What is the best way to declare a minimum and maximum date in HTML as the current date?

I have a question regarding setting the min/max date for a date input in my Angular 6 project. How can I ensure that only dates up to the current date are enabled? So far, I have attempted to initialize a new Date object in the ngOnInit function and set t ...

Tips on inserting a variable into an icon class in Angular 7

I am looking to add a unique icon to each item on my page, which is being generated inside of an *ngfor loop. For example: <i class="var"></i> Instead of 'var', I want to dynamically insert a variable provided by my service class in ...

Angular can redirect the path to the current page

I am looking for a way to handle empty paths in my routing module by redirecting to the current page. Can someone help me achieve this? Thank you in advance. Below are the routes defined: const routes: Routes = [ { path: 'students', co ...

Issue: Using the command 'typings search' successfully locates a package, however, when attempting to install it using 'typings install', the process fails

I am currently attempting to install the Google Auth2 typings using 'typings': > typings search gapi.auth2 This command returns: NAME SOURCE HOMEPAGE DESCRIPTION VERSIONS UPDATED gapi.auth2 d ...