transferring data between components in a software system

I received a response from the server and now I want to pass this response to another component for display. I attempted one method but ended up with undefined results. You can check out how I tried here: how to pass one component service response to other component in angular 2. Yesterday, after facing some routing issues, I made some changes and created separate components.

In mainsearch.component.ts:

export class MainsearchComponent {

  selected;
  skipCount: number = 0;
  errorMessage: string;
  searchedResults: any;

  searchObj: Object = {
    skipCount: this.skipCount
  };

  onChange(newValue) {
    console.log(newValue);
    this.selected = newValue;
  }

  constructor(private searchService: searchService, private router: Router) { }

  searchall() {

    console.log(this.searchObj);

    var searchData = this.searchObj;
    console.log(searchData);

    this.searchService.getSearchbyDistrictCategoryCity(this.searchObj).subscribe(
     data => {
      this.searchedResults = data;
      this.searchService.searchResults = data;
      console.log(this.searchedResults);
      console.log(this.searchService.searchResults);
      this.router.navigate(['/searchdetails']);
    },
    error => this.errorMessage = <any>error
    );
  }
}

In searchdetails.component.ts:

export class SearchdetailsComponent {

  searchedResults:any;

  constructor(private searchService: searchService) {
    this.searchedResults = this.searchService.searchResults;
    console.log(this.searchedResults);  
  }
}

In search.service.ts:

export class searchService {

  public searchResults;

  private searchAllUrl: string = "http://192.168.1.134:8000/app/school/searchbydistrictandcategoryandlocation"

  constructor(private http: Http) { }

  getSearchbyDistrictCategoryCity(searchObj) {
    // console.log(searchObj);
    // let body = JSON.stringify({ searchObj });
    let headers = new Headers();
    headers.append('Content-Type', 'application/json');

    return this.http.post(this.searchAllUrl, searchObj, { headers: headers })
      .map((response: Response) => response.json())
      .catch(this.handleError);
  }

  private handleError(error: Response | any) {

    let errMsg: string;
    if (error instanceof Response) {
      const body = error.json() || '';
      const err = body.error || JSON.stringify(body);
      errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
    } else {
      errMsg = error.message ? error.message : error.toString();
    }
    console.error(errMsg);
    return Observable.throw(errMsg);
  }
}

Now, the routing is working fine, but unfortunately, the data is not being received in the searchdetails component.

Answer №1

To efficiently share data across components in Angular, consider creating a factory service with an array of objects to store and access the data. Populate this array with your response data and then include the service tag in other components to utilize the shared data.

For more information, check out this resource

Answer №2

Learn how to utilize an asynchronous function below:

getSearchbyDistrictCategoryCity(searchObj) {
// console.log(searchObj);
// let body = JSON.stringify({ searchObj });
let headers = new Headers();
headers.append('Content-Type', 'application/json');

return this.http.post(this.searchAllUrl, searchObj, { headers: headers })
  .map((response: Response) => response.json())
  .catch(this.handleError);
}

In the code snippet above, you can see how the result is being assigned in the constructor:

export class SearchdetailsComponent {

  searchedResults:any;

  constructor(private searchService: searchService) {
    this.searchedResults = this.searchService.searchResults;
    console.log(this.searchedResults);  
  }
}

While it may appear that assigning searchService.searchResults to the search results in your SearchdetailsComponent is sufficient, the function in your search service may still be processing.

Rather than directly accessing searchService.searchResults from the template of your search details component, consider subscribing to the search function from your service within the search details as a more effective approach.

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

Testing onClick using Jest when it is not a callback function in props

I have discovered various ways to utilize mock functions in jest for spying on callback functions passed down to a component, but I have not found any information on testing a simple onClick function defined within the same component. Here is an example f ...

Is it possible to convert JSON to enum using TypeScript?

I have a JSON string that looks like the following. { "type": "A", "desc": "AAA" } or { "type": "B", "desc" "BBB" } etc. How can I utilize an enum in Ty ...

Is there a way to verify if the object's ID within an array matches?

I am looking to compare the ID of an object with all IDs of the objects in an array. There is a button that allows me to add a dish to the orders array. If the dish does not already exist in the array, it gets added. However, if the dish already exists, I ...

Integrating Paytm with Angular 6: A Step-by-

I am currently facing an issue where I am not being redirected to the paytm server's page after using the HTML form for integrating paytm in PHP. Can anyone provide assistance with this matter? ...

Trying to enter the function, but it exits without executing

I'm facing an issue with my function that involves making multiple calls to an observer. I need the function to wait until all the calls are complete before returning. I attempted putting the return statement inside the subscribe method, but it result ...

Using React and TypeScript to pass member variables

My component Child has a member variable that can change dynamically. While I am aware of passing props and states, is there a more elegant solution than passing member variables through props or other parameters? class Child extends React.Component< ...

The challenge of handling Set type in TypeScript errors

I'm currently facing two errors while trying to convert a function to TypeScript. The issue lies with the parameters, which are of type Set import type {Set} from 'typescript' function union<T>(setA: Set<T>, setB: Set<T>) ...

Can you explain how to utilize the 'npm' command and its functions?

Understanding npm: As I delve into various projects, they often direct me to utilize npm commands like this one: npm install -g node-windows I decided to explore npm by reading some blog posts and installing Node.js. However, upon attempting to run the a ...

TypeScript Angular Forms: Implementing correct typing for dynamic form fields

I have a formgroup that looks like this: this.formBuilder.group<{ id: number; nameDe?: FormControl<string>; nameFr?: FormControl<string>; nameIt?: FormControl<string>; }>({ id: value?.id || null }); The main foc ...

How should one handle the potential risks presented by literal types?

As I was translating a large JavaScript project into TypeScript, something caught my attention. Consider a module that looks like this: WinConstants.ts export = { "no_win":0, "win":1, "big_win":2, "mega_win":3 } I wanted to make it truly constan ...

Facing unexpected behavior with rxjs merge in angular5

import { Observable } from 'rxjs/Observable'; import 'rxjs/add/observable/merge'; this.data = this.itemsCollection.valueChanges() this.foo = this.afs.collection<Item>('products') .doc('G2loKLqNQJUQIsDmzSNahlopOyk ...

Troubleshooting: Angular version 4.3 Interceptor malfunctioning

I have been trying to implement new interceptors in Angular 4.3 to set the authorization header for all requests, but it doesn't seem to be working. I placed a breakpoint inside the interceptor's 'intercept' method, but the browser didn ...

Encountering an issue while developing a Discord bot using TypeScript

Hello, I'm currently working on creating a nick command for my discord bot in TypeScript, but I encountered an error. Here is the issue: Error: Expression expected.ts (1109) When I replace const mentionedMember = message? message.mentions.members? ...

Learn how to configure gulp-typescript to automatically generate individual JavaScript files for each TypeScript file within the same directory

My interest lies in utilizing the gulp-typescript module for handling typescript compilation. My goal is to set up a configuration where each typescript file translates into one javascript file in the corresponding directory, similar to how it works with t ...

A guide on determining the number of rows in an ag-grid with TypeScript and Protractor

I am currently working on extracting the number of rows in an ag-grid. The table is structured as follows: <div class="ag-body-container" role="presentation" style="height: 500px; top: 0px; width: 1091px;"> <div role="row" row-index="0" row-id="0 ...

Sending Svelte data to Javascript with an onclick event

In my Svelte store, I have an ASCII-Logo that I want to integrate into a button spanning two symbols ("-."). However, I do not want to split the ASCII into separate parts and just insert the button between them on my +page.svelte. Currently, I h ...

"Typescript throws a mysterious 'Undefined value' error post-assignment

I'm currently working on a task to fetch my customer's branding information based on their Id using Angular. First, I retrieve all the customer data: this.subscription = this.burstService.getBurst().subscribe(async(response) => { if (r ...

Adjusting the height of content in Angular Material 2 md-tab

I've recently started working with angular material and I'm facing an issue while trying to implement md-tab into my application. The problem is that I can't seem to style my tab content to take up the remaining height of the screen. Could s ...

Setting up Webpack for react-pdf in a Next.js application

In my Next.js application, I am utilizing the react-pdf library to generate and handle PDF files on the client side without involving the server. However, I am facing challenges in setting up Webpack for Next.js as I lack sufficient expertise in this area. ...

Access the Angular directive instance before it is actually rendered

Is it possible to access an Angular directive instance even if it has not been rendered yet? Let's say I have an app-component and a baz-directive. I want to be able to get the directive instance even if it is not currently shown or rendered in the D ...