【问题标题】:Angular 2 - One component trigger refresh of another component on the pageAngular 2 - 一个组件触发页面上另一个组件的刷新
【发布时间】:2017-03-10 00:31:42
【问题描述】:

我有一个 ComponentA 组件,它显示元素列表。此列表在ngOnInit 期间启动。

我有另一个组件 ComponentB 提供的控件可能会影响 ComponentA 中显示的元素列表。例如。可以添加一个元素。

我需要一种方法来触发 ComponentA 的重新初始化。

有人有想法吗?


详情

A 是一个 HeaderBar,带有一个显示“已保存搜索”列表的菜单

@Component({
  selector: 'header-bar',
  templateUrl: 'app/headerBar/headerBar.html'
})
export class HeaderBarComponent implements OnInit{
  ...
  ngOnInit() {
    // init list of savedSearches
    ...
  }
}

B 是一个可以保存搜索的 SearchComponent

@Component({
  selector: 'search',
  templateUrl: 'app/search/search.html'
})
export class SearchComponent implements OnInit {
  ...
}

【问题讨论】:

  • 使用可观察的服务? angular.io/docs/ts/latest/cookbook/…
  • ComponentA 正在使用一个服务返回一个可观察的元素列表。但是在 ngOnInit 期间返回列表后,它就完成了。 (这是一个http-get)
  • 你创建你自己的 observable,所以你可以在组件 B 做某事时通知组件 A。只需阅读他们非常解释性的文档
  • A,我知道了...应该先阅读您的链接。非常感谢!

标签: angular typescript angular2-components


【解决方案1】:

您需要提供组件,并将其注入组件的构造函数中,您需要像我一样调用其他组件的 ngOnInit。

Plunker 演示:https://plnkr.co/edit/M0d65wHjfg4KfwaQ5mPM?p=preview

//our root app component
import {Component, NgModule, VERSION, OnInit} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'

@Component({
  selector: 'my-app',
  template: `
    <div>
      <h2>Hello {{name}}</h2>
       <comp-one></comp-one>
       <comp-two></comp-two>
    </div>
  `,
})
export class App {
  name:string;
  constructor( ) {
    this.name = `Angular! v${VERSION.full}`
  }
}

// ComponentOne with ngOnInit

@Component({
  selector: 'comp-one',
  template: `<h2>ComponentOne</h2>`,
})
export class ComponentOne implements OnInit {

  ngOnInit(): void {
    alert("ComponentOne ngOnInit Called")
  }

}

// Added provider of ComponentOne here and injected inside constructor the on button click call ngOnInit of ComponentOne from this component
@Component({
  providers:[ComponentOne],
  selector: 'comp-two',
  template: ` Component Two: <button (click)="callMe()">Call Init of ComponentOne</button>`,
})
export class ComponentTwo implements OnInit {

   constructor(private comp: ComponentOne ) {
    this.name = `Angular! v${VERSION.full}`
  }
  public callMe(compName: any): void {
    this.comp.ngOnInit();
  }


}
@NgModule({
  imports: [ BrowserModule ],
  declarations: [ App, ComponentOne, ComponentTwo ],
  bootstrap: [ App ]
})
export class AppModule {}

【讨论】:

  • 调用ngOnInit 是一个补丁。您可以使用BehaviourSubject。它是 Observer 和 Observable,两者都是。 Refer this link
猜你喜欢
  • 2021-02-06
  • 2017-10-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-20
  • 1970-01-01
  • 1970-01-01
  • 2017-06-24
  • 2016-09-28
相关资源
最近更新 更多