我正在测试 signalState,我想知道如何将多个参数传递给
rxMethod
函数。
在我的商店.ts:
constructor() {
this.fetchData(stringArray1$, observable2$)
}
readonly fetchData = rxMethod<--?-->(
pipe(
doSomething(),
)
)
rxMethod
函数的参数需要传入什么?
rxMethod
是可观察量的入口点 - 它不能有多个参数,因为任何可观察量一次只能传递一个值。
使用带有键的对象,而不是使用多个参数。
https://ngrx.io/api/signals/rxjs-interop/rxMethod
看看这个:
import { Component, Injector, effect, inject, signal } from '@angular/core';
import { DatePipe } from '@angular/common';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { rxMethod } from '@ngrx/signals/rxjs-interop';
import { signalStore, withMethods, withState, patchState } from '@ngrx/signals';
import { bootstrapApplication } from '@angular/platform-browser';
import 'zone.js';
import { pipe, tap, timer } from 'rxjs';
interface RxInput {
input: string;
date: Date;
}
interface RxValue {
value: string;
date: Date;
}
interface State {
input: RxInput;
value: RxValue;
}
const Store = signalStore(
{ providedIn: 'root' },
withState<State>({
input: { input: '', date: new Date() },
value: { value: '', date: new Date() },
}),
withMethods((store) => ({
setInput: (input: RxInput) => {
patchState(store, (state: State) => {
return {
...state,
input: {
input: input.input,
date: input.date,
},
};
});
},
inputPipe: rxMethod<RxInput>(
pipe(
tap((input) =>
patchState(store, (state: State) => {
return {
...state,
value: {
value: `rxValue-${input.input}`,
date: input.date,
},
};
})
)
)
),
}))
);
@Component({
selector: 'app-root',
standalone: true,
template: `
<h1>Hello from {{ name }}!</h1>
<h2><b>INPUT</b></h2>
<p><b>Date:</b> {{store.input.date() | date:'YYYY-MM-dd HH:mm:ss'}}</p>
<p><b>Value:</b> {{store.input.input()}}</p>
<h2><b>VALUE</b></h2>
<p><b>Date:</b> {{store.value.date() | date:'YYYY-MM-dd HH:mm:ss'}}</p>
<p><b>Value:</b> {{store.value.value()}}</p>
`,
imports: [DatePipe],
})
export class App {
store = inject(Store);
name = 'Angular';
constructor() {
this.store.inputPipe(this.store.input);
timer(1000, 2000)
.pipe(
tap((value) =>
this.store.setInput({ input: value.toString(), date: new Date() })
),
takeUntilDestroyed()
)
.subscribe();
}
}
bootstrapApplication(App);