Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/467.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何从Angular 7中的另一个组件更新视图?_Javascript_Angular - Fatal编程技术网

Javascript 如何从Angular 7中的另一个组件更新视图?

Javascript 如何从Angular 7中的另一个组件更新视图?,javascript,angular,Javascript,Angular,我想从导航栏刷新我的卡片集,导航栏是app.component.html的一部分,所以我准备了refresh()函数 调用它时,它会更新变量卡,但不会在mainView.html中的ngFor on html元素中呈现它 如果我从mainView.html中的html元素调用(如(单击)=“loadCards()”),它会呈现更新集,但如果在app.component.html中执行相同的((单击)=“refresh()”),则不会呈现更新集 导出类AppComponent{ ... 构造函数

我想从导航栏刷新我的卡片集,导航栏是app.component.html的一部分,所以我准备了refresh()函数

调用它时,它会更新变量卡,但不会在mainView.html中的ngFor on html元素中呈现它

如果我从mainView.html中的html元素调用(如(单击)=“loadCards()”),它会呈现更新集,但如果在app.component.html中执行相同的((单击)=“refresh()”),则不会呈现更新集


导出类AppComponent{
...
构造函数(专用路由器:路由器,专用mMainView:MainView){}
刷新(){
console.log('done');
这个.mMainView.loadCards();
}
...
}
更新 尝试使用@Input(),但无法使其正常工作。我按照accepted answer中的解释实现了RefreshService,现在我能够从其他组件刷新内容


感谢大家的快速响应。

您试图将MainView用作依赖项,但它不是可注入依赖项。如果可能,尝试在应用程序组件和MainView之间使用输入/输出。如果MainView不是AppComponent的子组件,则将用于将卡加载到服务中的逻辑抽象出来,并将其注入两者。

您可以通过两种方式实现组件交互

(i) 如果组件彼此相关,则使用共享数据的常见且直接的方法。它通过使用
@Input()
装饰器来允许通过模板传递数据


(ii)如果组件彼此不相关,您可以使用共享服务,在两个组件之间使用subject to,第一种方式:使用共享服务

你需要引入一种管理汽车状态的服务

在这种情况下,可以为此引入一个
行为主体
,如下所示:

this.myService.getRefresh().subscribe((value: boolean) => {
    if(value) {

      this.loadCards()
    }

})

您的服务:

private刷新:BehaviorSubject=newbehaviorsubject(false)

在AppComponent类中

  • 第一:将服务作为依赖项注入
  • 第二:在刷新方法中设置可观察值
e、 g类似于这样:


public refresh(){
    this.myService.setRefresh(true);
}


第二种方法:使用@Input Decorator向下传递值

我认为问题来自调用MainView的方式,它似乎不会触发摘要。我认为正确的方法是将您的卡片数组作为输入传递给组件
[cards]=cards
,然后直接从子组件修改卡片数组。
this.myService.getRefresh().subscribe((value: boolean) => {
    if(value) {

      this.loadCards()
    }

})


public refresh(){
    this.myService.setRefresh(true);
}