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