【发布时间】:2017-09-22 12:57:59
【问题描述】:
我正在使用 rxjs BehaviorSubject 创建一个服务,在从 Component1 发送值并在 Component3 中订阅时,我得到 Component3 中的值,这是实现的
服务文件
`import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
@Injectable()
export class UserService {
constructor() { }
// Observable navItem source
public _navItemSource = new BehaviorSubject(undefined);
// Observable navItem stream
navItem$ = this._navItemSource.asObservable();
// service command
changeNav(nu) {
this._navItemSource.next([...nu]);
}
}`
组件1
`this._userService.changeNav(self.notificationslist);`
组件3
`this.subscription = this._userService.navItem$.subscribe(item =>
this.item1 = item);`
现在我想在另一个组件(Component2)中使用相同的服务来向同一个组件Component3发送一些不同的值
组件2
`this._userService.changeNav(this.updatedFlag);`
组件3
`this.subscription = this._userService.navItem$.subscribe(item =>
this.item1 = item);`
然后在 Component3 上订阅它时,我应该从 Component1 和 Component2 中获取所有值。 所以我更新了我的服务文件,但我收到以下错误
caused by: this._navItemSource.asObservable(...).scan is not a function
由于我是 rxjs 的新手,请纠正我哪里出错了。
更新的服务文件
`import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
@Injectable()
export class UserService {
constructor() {
}
// Observable navItem source
public _navItemSource = new BehaviorSubject(undefined);
// Observable navItem stream
navItem$ = this._navItemSource.asObservable().scan((acc, one) =>(acc +
one));
// service command
changeNav(nu) {
this._navItemSource.next([...nu]);
}
}`
【问题讨论】:
-
确保您导入扫描运算符!导入“rxjs/add/operator/scan”;
-
非常感谢@JayDeeEss,错误是由于未导入扫描运算符,但我只获取 Component1 的值而不是来自 Component2,我从 Component1 传递一个数组,从 Component2 传递一个值
-
如果一个是数组而另一个是单值,则您的函数看起来不正确。您要么必须以某种方式从两者返回数组并合并为一个,要么返回一个 json,其中第一个是数组,第二个是单个值,因为扫描总是会返回一个值
-
好的,我已经在 Component2 中定义了 updatedFlag = [],但我想只是为了提供信息,我会告诉
-
好的,那么你可以使用 concat() 来合并 2 个数组,如果这是你想要的 developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…