如何从Angular 7中的另一个组件更新视图? [英] How to update view from another component in Angular 7?

查看:55
本文介绍了如何从Angular 7中的另一个组件更新视图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从属于 app.component.html 的导航栏中刷新卡集,所以我准备了 refresh()函数.

I'd like to refresh my card set from navigation bar which is part of app.component.html so I prepared refresh() function.

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

When it is called it does update variable Cards but doesn't render it in ngFor on html element in mainView.html.

如果我从 mainView.html 中的html元素调用(如(click)="loadCards()" ),它会呈现更新的集,但是如果相同((click)="refresh()" )在 app.component.html 中完成.

It does render updated set if I call from html element in mainView.html (as (click)="loadCards()") but not if the same ((click)="refresh()") is done in 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,现在我可以从其他组件中刷新内容.

Update

Tried with @Input() but couldn't get it work. I implemented RefreshService as explained in accepted answer and now I'm able to refresh content from other components.

谢谢大家的快速反应.

推荐答案

主要方法:使用共享服务

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

You need to introduce a service that manage the state of your car.

在这种情况下,为此引入一个可能是有用的:

In this case it may be usefull to introduce for this a BehaviorSubject like this:

您的服务

私有刷新: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挂钩中订阅您的可观察对象,例如:

Inside your MainView class - First: inject your service as dependency - Second: Subscribe to your observable inside OnInit hook e.g like this:

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

      this.loadCards()
    }

})

在您的AppComponent类内部

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

例如:


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

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

这篇关于如何从Angular 7中的另一个组件更新视图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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