passing one component data to other component

2019-06-01 05:00发布

问题:

I am getting response from server,I want pass this response to other component for displaying. I tried in one way but getting undefined. Tried this way how to pass one component service response to other component in angular 2. yesterday got the results faced routing. Changed little bit created separated components.

mainsearch.component.ts:

export class MainsearchComponent {

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

  searchObj: Object = {

    skipCount: this.skipCount

  };

  onChange(newVlaue) {
    console.log(newVlaue);

    this.selected = newVlaue;
  }

  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
    );
  }
}

searchdetails.component.ts:

export class SearchdetailsComponent {

  searchedResults:any;

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

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 routing working fine, but data is not getting in searchdetails component

回答1:

You can define a factory service (shared data service) and have a array of objects there then fill array from your response and use this array in other component by including the service tag on component.

you can refer this link



回答2:

This is a asynchrounous function:

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);
}

Here you are assigning the result in the constructor:

export class SearchdetailsComponent {

  searchedResults:any;

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

At the moment you are assigning the searchService.searchResults to the search results in your SearchdetailsComponent the function in your search service may not be complete.

You could access the searchService.searchResults from the template of your search details component because it's public. A better way would be to subscribe to the search function from your service in your search details too.