'rxjs - deprecated subscribe with multiple parameter
rxjs 6.4. started to deprecate subscribe with multiple parameters. To some extend I understand but on a practical level I have my problems. Especially when I specify the type received parameter. E.g.
subscribe((response: boolean | LibDto) => {
this.errorCmpt.showMsgShort('save success');
}, () =>
this.errorCmpt.showMsgShort('save failure')
)
When I try to follow the given link than I thought I can rewrite the function like:
subscribe({
complete:(response: boolean | LibDto) => {
this.errorCmpt.showMsgShort('save success');
}, error: () =>
this.errorCmpt.showMsgShort('save failure')
})
But this fails
Overload 1 of 3, '(observer?: Partial<Observer<boolean | LibDto>>): Subscription', gave the following error.
Type '(response: any) => void' is not assignable to type '() => void'.
Overload 2 of 3, '(next: (value: boolean | LibDto) => void): Subscription', gave the following error.
Argument of type '{ complete: (response: any) => void; }' is not assignable to parameter of type '(value: boolean | LibDto) => void'.
Object literal may only specify known properties, and 'complete' does not exist in type '(value: boolean | LibDto) => void'.
Overload 3 of 3, '(next?: (value: boolean | LibDto) => void, error?: (error: any) => void, complete?: () => void): Subscription', gave the following error.
Argument of type '{ complete: (response: any) => void; }' is not assignable to parameter of type '(value: boolean | LibDto) => void'.
Object literal may only specify known properties, and 'complete' does not exist in type '(value: boolean | LibDto) => void'. ref-source-dialog.component.ts
If I try complete with a function without parameters it works. How to write it correctly?
Solution 1:[1]
RxJS Observers
RxJS observers have 3 callbacks that an observable will call. Here's a simplified interface:
interface Observer<T>{
next: (a:T) => void;
error: (e:Error) => void;
complete: () => void;
}
These two calls are treated (basically the same)
stream$.subscribe(console.log);
stream$.subscribe({next: console.log});
That is to say, if you give subscribe a function, it will assume the function is for the Observer's next callback.
If you look at the interface above, you'll note that an Observer's complete callback doesn't take any arguments. You can't get a response inside a complete callback.
Toward an Answer
Perhaps you meant:
subscribe({
next: (response: boolean | LibDto) => {
this.errorCmpt.showMsgShort('save success');
},
error: () => {
this.errorCmpt.showMsgShort('save failure');
}
});
or
subscribe({
complete: () => {
this.errorCmpt.showMsgShort('save success');
},
error: () => {
this.errorCmpt.showMsgShort('save failure');
}
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Mrk Sef |
