typescript 如何从另一个组件实时刷新一个组件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/50488127/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 05:26:07  来源:igfitidea点击:

how to refresh one component from another component real time?

angulartypescript

提问by beginer_programer

Hi i have two components A&B. In A i am having a drop down which contains car models.In B i am having one more drop down contain model year.If I am selecting a car from drop down A the available year associated with that selected car will display.All are working fine but Iam facing one issue that from B if i am changing any particular year A component not refreshing immediately .After page reload only am getting the new values.How i can solve this. Ngonint() call is not a good way because i am having enough methods inside that?please help

嗨,我有两个组件 A&B。在 A 中,我有一个包含汽车模型的下拉列表。在 B 中,我还有一个包含模型年份的下拉列表。如果我从下拉列表 A 中选择一辆车,与所选汽车相关的可用年份将显示。所有都在工作很好,但我面临一个来自 B 的问题,如果我更改任何特定年份 A 组件不会立即刷新。页面重新加载后只会获得新值。我该如何解决这个问题。Ngonint() 调用不是一个好方法,因为我在里面有足够的方法?请帮忙

回答by Anuradha Gunasekara

You can use a service for this.

您可以为此使用服务。

You can communicate between components using a service as described in the angular official documentation , Component Interaction.

您可以使用 angular 官方文档Component Interaction 中描述的服务在组件之间进行通信。

Hoe this helps.

锄头这有帮助。

回答by djain4

You can use Subjects for this.

您可以为此使用主题。

Lets consider an Interface dateRange

让我们考虑一个接口 dateRange

IDateRange {
   availableYear: string
}

Create a subject in a commonService.ts like below

在 commonService.ts 中创建一个主题,如下所示

private updateLists = new Subject<IDateRange>();
updateListsObs = <Observable<IDateRange>>this.updateLists;

updateListFn(_dateRange : IDateRange ) {
 this.updateLists.next(_dateRange);
}

In your Component A inject CommonService and subscribe to observable updateListsObs like below

在您的组件 A 中注入 CommonService 并订阅如下所示的可观察 updateListsObs

this.CommonService.updateListsObs
.subscribe(
(response) => {console.log("You will get date range in response which can be used to filter Car list in Component A ")}
)

Then in your Component B inject CommonService and call UpdateListFn

然后在您的组件 B 中注入 CommonService 并调用 UpdateListFn

let dateRange: IDateRange = {
 availableYear: "2018"
}
this.CommonService.updateListFn(dateRange);

For detail description you can referthis link

有关详细说明,您可以参考此链接