BehaviorSubject of a type in angular

Tej*_*nge 0 rxjs angular

Let's say I have a model User.

I want to create a BehaviorSubject of type User as below:

 private userSource = new BehaviorSubject<User>({});
Run Code Online (Sandbox Code Playgroud)

With this statement I'm getting the following error:

  Argument of type '{}' is not assignable to parameter of type 'User'
Run Code Online (Sandbox Code Playgroud)

Could anyone help me how define a BehaviorSubject of type User

Sur*_*yan 6

new BehaviorSubject<User>({}) with this you have passed an initial value for the BehaviorSubject. Cause {} has no type detection, you get error.

You need to pass an User type. Provide properties for that type in the {} like

private userSource = new BehaviorSubject<User>({ /* properties */ });
Run Code Online (Sandbox Code Playgroud)

If you don't need initial value. you can use ReplaySubject with replay count set to 1

new ReplaySubject<User>(1)
Run Code Online (Sandbox Code Playgroud)

This will provide same functionality without initial value.


mar*_*tin 5

那是因为{}是一个对象与User(实际上它是一个空对象)没有相同的属性。

您可以通过强制转换{}any

new BehaviorSubject<User>({} as any);
Run Code Online (Sandbox Code Playgroud)

  • 为什么不使用 `newBehaviorSubject&lt;User&gt;({} as User);` 而不是 `newBehaviorSubject&lt;User&gt;({} as any);` (2认同)

ham*_*zox 5

您需要传递User类型。{}是一个初始值,不遵循 的架构/类型User
如果您想传递一个空值,请使用nullexcept{}