我收到服务器的响应,我希望将此响应传递给其他组件进行显示。我尝试过一种方式,但未定义。 试过这种方式how to pass one component service response to other component in angular 2。 昨天得到的结果面临路由。改变了一点点创建的分离组件。
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);
}
}
现在路由工作正常, 但是数据没有进入searchdetails组件
答案 0 :(得分:0)
您可以定义工厂服务(共享数据服务)并在其中包含一组对象,然后从响应中填充数组,并通过在组件上包含服务标记在其他组件中使用此数组。
您可以参考此link
答案 1 :(得分:0)
这是一个异步函数:
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);
}
在这里,您将在构造函数中分配结果:
export class SearchdetailsComponent {
searchedResults:any;
constructor(private searchService: searchService) {
this.searchedResults = this.searchService.searchResults;
console.log(this.searchedResults);
}
}
当您将searchService.searchResults
分配给SearchdetailsComponent
中的搜索结果时,搜索服务中的功能可能不完整。
您可以从搜索详细信息组件的模板访问searchService.searchResults
,因为它是公开的。
更好的方法是在搜索详细信息中订阅服务中的搜索功能。