我正在从服务器中获得响应,我想将此响应传递给其他组件以显示。我以某种方式尝试了,但不确定。尝试了如何将一个组件服务响应传递给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组件
您可以定义出厂服务(共享数据服务),并在那里有一系列对象,然后从响应中填充数组,并在其他组件中使用此数组,通过在组件上包含服务标签。
您可以参考此链接
这是一个异步功能:
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
,因为它是公开的。更好的方法是也在搜索详细信息中从您的服务中订阅搜索功能。