如何在角度2中将一个组件服务响应传递给另一组件 [英] how to pass one component service response to other component in angular 2

查看:55
本文介绍了如何在角度2中将一个组件服务响应传递给另一组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对角度4很陌生 从一个组件中的服务器获取响应,而我希望其他组件中的此响应对象如何访问

I am new to angular 4, getting response from server in one component and I want this response object in other component how to access

app.component.ts:

app.component.ts:

export class AppComponent {
  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;
          console.log(this.searchedResults);
          this.router.navigate(['/searchdetails/'])
        },
        error => this.errorMessage = <any>error);
  }
}

我想将searchedResults变量的结果放入搜索详细信息之类的其他组件中 如何获得这个.

I want searchedResults variable result in other component like search details how to get this.

谢谢!

推荐答案

您可以将搜索结果保存在searService中,然后从那里返回.为此,只需在您的服务中添加searchResults属性,并使用当前的搜索结果对其进行更新.看起来类似于以下内容:

You can save the search results in your searService and get it back from there. For this just add the searchResults property in your service and update it with the current search results. It would look something like the following:

export class SearchService {
  public searchResults;

  ... 
}

,只要您想更新搜索结果,就可以执行以下操作: ``

and whenever you want to update the search results you would do: ```

this.searchService.getSearchbyDistrictCategoryCity(this.searchObj).subscribe(data=>{
  this.searchedResults = data;
  this.searchService.searchResults = data; 
},error=>this.errorMessage= <any>error);

您还可以覆盖您在服务中找到结果时自动更新searchResults属性的搜索功能.

you can also overwrite your search function that you update the searchResults property automatically when finding results in your service.

在其他组件中,您可以仅使用服务中的属性

and in the other component you can just user the property from the service

this.searchedResults = this.searchService.searchResults;

如果希望组件随新日期自动更新,则必须将userService直接绑定到输入或添加用于数据更改的侦听器.

If you want that the component updates automatically with the new date you either have to bind the userService directly to the input or add a listener for the data change.

这篇关于如何在角度2中将一个组件服务响应传递给另一组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆