html - 使用事件发射器在 Angular 中发送组件下拉值两个级别

标签 html css angular angular8

我正在尝试在两个不相关的组件之间发送数据。我正在尝试利用事件发射器输出和地址服务。

如何获取第一个地址下拉事件发射器,以将数据传递给服务?该服务然后可以将数据发送到接收器。

export class AddressDropdownComponent implements OnInit {

  addresses: any[] = [];
  @Input() addressDefaultItem: AddressDto;
  @Input() selectedAddress: any;
  @Input() TxtField: string = 'addressDescription';
  @Output() selectedItemOutput = new EventEmitter();

  constructor(private addressService:AddressServiceProxy ) { }

  ngOnInit() {
  }

  statusSelectedItemChanged(e) {
    this.selectedAddress = e;
  }

仍在致力于此地址服务

export class AddressService {

  private messageSource = new BehaviorSubject("default message");
  currentMessage = this.messageSource.asObservable();

  constructor() { }

  changeMessage(message: string) {
    this.messageSource.next(message)
  }

}

资源:以下仅针对亲子,寻找不相关的“祖父”或“兄弟”案例

What is the best way to use nested components in Angular 4 and calling a method of a parent to child and vice versa?

最佳答案

所以你有一个源,比方说 ComponentA,在它之上的一些组件比方说 ComponentV

要连接它们,您首先需要通过服务连接它们。如果它们中的每一个只有一个实例,您可以使用单例服务(在 @Injectable 装饰器中有 providedIn: 'root')。但是,如果您可以有多个包含 ComponentAComponentV,则需要在层次结构的顶层提供此服务。在这种情况下,ComponentV 必须有 providers: [SomeService] 才能在创建 ComponentV 时创建新的服务实例。

然后在SomeService中定义一些prop来共享数据。

例如你最终得到

// SomeService contents
...
// create a source
private dataSource$ = new Subject();
// Expose as observable so it's value can be changed
// only via exposed method (dataChanged)
data$ = this.dataSource$.asObservable();

// public API to pass new data
dataChanged(data) {
  this.dataSource$.next(data);
}
...

然后您将此服务注入(inject) ComponentA 并定义一个函数来发出数据更改。

// ComponentA contents
...
constructor(private readonly someService: SomeService) {}

onDataChange(data) {
  // here we notify about data change
  this.someService.dataChanged(data);
}
...

然后你需要订阅顶层组件中的可观察对象

// CompoentV contents
...
constructor(private readonly someService: SomeService) {
  // here we subsribe to changes and use whatever handler we need
  this.someService.data$.subscribe(data => {
    // some logic goes here or pass this data to a method
  });
}
...

这允许人们在不相关或松散相关的组件之间共享一些状态或事件。

关于html - 使用事件发射器在 Angular 中发送组件下拉值两个级别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58678300/

相关文章:

angular - ngx-translate: 翻译 html 中的字符串

jquery - html元素比较

javascript - 点击并重新排序

javascript - 如何将元素添加到 jQuery UI Accordion header ?

css - 为什么 CSS transition-duration 对子元素不起作用?

javascript - 如何制作 HTML5 旋转列表/旋转轮选择器/选择器

python - Selenium Python sel.click ("css=input.smthg")?

Angular CLI 删除带前缀的 CSS

javascript - 两次提交调用函数

Angular 无法读取组件/表单中未定义的属性