【问题标题】:How to update view from another component in Angular 7?如何从 Angular 7 中的另一个组件更新视图?
【发布时间】:2021-10-24 17:33:13
【问题描述】:

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

当它被调用时,它会更新变量 Cards 但不会在 ma​​inView.html 的 html 元素上的 ngFor 中呈现它。

如果我从 ma​​inView.html 中的 html 元素调用(如 (click)="loadCards()"),它会呈现更新的集合,但如果相同则不会( (click)="refresh()") 在 app.component.html 中完成。


export class MainView implements OnInit {

  constructor(private mMainController: MainController) {}

  Cards: any = [];

  ngOnInit() {
    this.loadCards();
  }

  loadCards() {
    this.mMainController.getAllCards().subscribe(
      (data) => {this.Cards = data); },
      (error) => {},
      () => {console.log(this.Cards));
  }

...
}

export class AppComponent {
  ...

  constructor(private router: Router, private mMainView: MainView) {}

  refresh(){
    console.log('done');
    this.mMainView.loadCards();
  }
  ...
}

更新

尝试使用 @Input() 但无法正常工作。我按照接受的答案中的说明实现了 RefreshService,现在我可以刷新其他组件的内容。

感谢大家的快速回复。

【问题讨论】:

  • 我认为问题出在您调用 MainView 的方式上,这似乎不会触发摘要。我认为正确的方法是将您的卡片数组作为输入传递给您的组件[cards]=cards,然后直接从子组件修改卡片数组。

标签: javascript angular


【解决方案1】:

第一种方式:使用共享服务

您需要引入一项管理汽车状态的服务。

在这种情况下,为此引入BehaviorSubject 可能会很有用:

您的服务:


private refresh: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false);

public getRefresh(): Observable<boolean> {

   return this.refresh.asObservable();
}

public setRefresh(value: boolean): void {

   this.refresh.next(value);
} 

在 MainView 类中

  • 首先:将服务注入为依赖项
  • 第二:在 OnInit 钩子中订阅您的 observable,例如:
this.myService.getRefresh().subscribe((value: boolean) => {
    if(value) {

      this.loadCards()
    }
  
})

在您的 AppComponent 类中

  • 首先:将服务注入为依赖项
  • 第二:在刷新方法中设置可观察对象的值。

例如这样的:


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

第二种方式:使用@Input 装饰器向下传递值

【讨论】:

    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

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

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

      (ii) 如果组件彼此不相关,您可以在两个组件之间使用主题为 communicate 的共享服务

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-10-01
        • 2017-02-04
        • 1970-01-01
        • 1970-01-01
        • 2021-09-09
        • 2017-06-12
        • 1970-01-01
        相关资源
        最近更新 更多