要让您的价值从Subject 中推出,请从它和subscribe 创建一个Observable。
如果你想要一个本地版本的值,由于对象在 JavaScript 中是通过引用传递的,你需要获取一个副本,所以在订阅时创建一个新对象。
您可以使用Spread Syntax 来做到这一点。
然后您可以为本地对象分配您喜欢的任何值,而不会影响Subject。
例如(StackBlitz)
const theRuleSbj = new BehaviorSubject<Rule>(null);
const theRule$ = theRuleSbj.asObservable();
// The observable will emit null on the initial subscription
// Subject might be a better fit
theRule$.subscribe(rule => {
console.log(`Subscription value:`, rule);
// Use object spread to create a new object for your component
this.rule = { ...rule };
});
// Update the Subject, it will console log new value
// and update your local value
theRuleSbj.next({ name: 'Name 1'});
// Update your local value, does not effect your Subject value
this.rule.name = 'Name 2';
// Confirm that they are differant
console.log(`Subject Value:`, theRuleSbj.getValue());
console.log(`Local Value`, this.rule);
// Be careful as when you update the Subject, your local value will be updated
theRuleSbj.next({ name: 'Name 3'});
console.log(`Subject Value (after subject update):`, theRuleSbj.getValue());
console.log(`Local Value (after subject update)`, this.rule);
请注意,订阅后,您会将主题值的所有更新推送到您的本地值,您可能希望也可能不希望这种情况发生。
如果您只想要组件中的一个值,您可以pipe() observable 并使用take(1) 来获取一个值,但是当您将Subject 初始化为BehaviourSubject 时,您只会获取null 值。您可能希望将其更改为 Subject,以便在将第一个值推送到 Subject 时,您的组件会收到它。
const theRuleSbj = new Subject<Rule>();
/* other code omitted */
theRule$
.pipe(take(1))
.subscribe(rule => {
console.log(`Subscription value:`, rule);
this.rule = { ...rule };
});