通过BehaviorSubject共享数据并绑定到结果,不确定是否可以?

时间:2019-05-07 12:32:02

标签: angular typescript behaviorsubject

我正在使用一项服务来保存一些我需要在不同组件之间共享的数据。 为了使我的html更加整洁,我将表单拆分为多个包含几个字段的组件。

这是一个例子。

服务:

<html>
<body>
<div class="container">
	<div class="above">
		Some text about the images
	</div>
	<div class="middle">
		<div class="images">
			<div class="image">
				<img src="https://dummyimage.com/200x200/000/fff" alt="" />
			</div>
			<div class="image">
				<img src="https://dummyimage.com/200x200/000/fff" alt="" />
			</div>
			<div class="image">
				<img src="https://dummyimage.com/200x200/000/fff" alt="" />
			</div>
			<div class="image">
				<img src="https://dummyimage.com/200x200/000/fff" alt="" />
			</div>
			<div class="image">
				<img src="https://dummyimage.com/200x200/000/fff" alt="" />
			</div>
			<div class="image">
				<img src="https://dummyimage.com/200x200/000/fff" alt="" />
			</div>
			<div class="image">
				<img src="https://dummyimage.com/200x200/000/fff" alt="" />
			</div>
			<div class="image">
				<img src="https://dummyimage.com/200x200/000/fff" alt="" />
			</div>
			<div class="image">
				<img src="https://dummyimage.com/200x200/000/fff" alt="" />
			</div>
			<div class="image">
				<img src="https://dummyimage.com/200x200/000/fff" alt="" />
			</div>
		</div>
	</div>
	<div class="below">
		<button>Ok</button>
		<button>Cancel</button>
	</div>
</div>
</body>
</html>

(注意:代码是示例)

组件1:

import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';

@Injectable()
export class DataService {

  private mAccount$ = new BehaviorSubject({accountdatahere});

  // subscribe to this
  public get Account$(): Observable<IAccount> {
     return this.mAccount$.asObservable();
  }

  constructor() { }

  SetAccount(acc) {
    this.mAccount$.next(acc); // this gets called my my parent component (not depicted)
  }

}

组件2:

import { Component, OnInit } from '@angular/core';
import { DataService } from "../data.service";

@Component({
  selector: 'app-first',
  template: `
    {{account}}
  `,
})
export class FirstComponent implements OnInit {

  account: IAccount;

  constructor(private data: DataService) { }

  ngOnInit() {
    this.data.Account$.subscribe(acc => {
        this.account = acc;
        this.account.Name = 'Changed from Component 1';
     })

  }

}

我遇到的问题是,组件2反映了对组件1所做的更改,而不必调用'Account $ .next()'。

这是BehaviorSubject的预期用途,还是我做错了什么? 如果我想通过使用'.next()'来做到这一点,那么我将必须在所有输入字段上进行更改检测,然后调用'.next()'还是我的设计错误,我应该保留所有html吗?一个组成部分?

有什么建议吗?

0 个答案:

没有答案