行为主体初始值为空?

Non*_*one 34 rxjs typescript angular

private customer: Subject<Object> = new BehaviorSubject<Object>(null);

setCustomer(id, accountClassCode) {
    this.customer.next({'id': id, 'accountClassCode': accountClassCode});
}

getCustomer() {
    return this.customer.asObservable();
}
Run Code Online (Sandbox Code Playgroud)

我正在使用这部分代码但是我收到的错误找不到null的id.有没有解决方案来获得非null的初始值?

Est*_*ask 70

目的BehaviorSubject是提供初始价值.它可以是null或其他任何东西.如果无法提供有效的初始值(当用户ID尚未知晓时),则不应使用它.

ReplaySubject(1)提供类似的行为(在订阅时发出最后一个值),但在设置之前没有初始值next.

它可能应该是

private customer: Subject<Object> = new ReplaySubject<Object>(1);
Run Code Online (Sandbox Code Playgroud)

  • @Simon_Weaver 当前默认值(2019 年 11 月)是无穷大。需要设置 1。https://rxjs-dev.firebaseapp.com/api/index/class/ReplaySubject (11认同)
  • 如果未指定,则默认值为1,因此`new ReplaySubject &lt;Foo&gt;()`更好。指定类型在运行时不会执行任何操作,但在编译时提供类型安全。 (4认同)

Bel*_*ash 19

由于对象可以为 null,因此更好的选择是像这样推断类型

 private customer = new BehaviorSubject<Customer|null>(null);
Run Code Online (Sandbox Code Playgroud)


SrA*_*Axi 5

尝试以这种方式构建您的服务:

服务:

@Injectable()
export class MyService {
    customerUpdate$: Observable<any>;

    private customerUpdateSubject = new Subject<any>();

    constructor() {
        this.customerUpdate$ = this.customerUpdateSubject.asObservable();
    }

    updatedCustomer(dataAsParams) {
        this.customerUpdateSubject.next(dataAsParams);
    }
}
Run Code Online (Sandbox Code Playgroud)

请记住添加MyService到提供商。

在更新客户端的地方(如果是这种情况),您可以执行以下操作:

组件(触发的组件):

constructor(private myService: MyService) {
        // I'll put this here, it could go anywhere in the component actually
        // We make things happen, Client has been updated
        // We store client's data in an object
        this.updatedClient = this.myObjectWithUpdatedClientData;  // Obj or whatever you want to pass as a parameter
        this.myService.updatedCustomer(this.updatedClient);
    }
Run Code Online (Sandbox Code Playgroud)

组件(已订阅的组件):

this.myService.customerUpdate$.subscribe((updatedClientData) => {
            // Wow! I received the updated client's data
            // Do stuff with this data!
        }
    );
Run Code Online (Sandbox Code Playgroud)

据我了解,您正在尝试将数据从一个组件传递到另一个组件。您获取客户的数据并通过您的应用程序将其发送到另一个组件,对吗?这就是我发布此解决方案的原因。

如果您对其他类型的订阅感兴趣,请阅读以下内容:

Angular 2 特殊 Observables (Subject / Behaviour subject / ReplaySubject)