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.