Issue
I have an Angular
application in which errors are beginning to appear in the subscribe
that they are deprecated.
This is my subscribe:
this.route.params.subscribe(params => {
this.clienteId = +params['clienteId'];
this.isNew = !this.clienteId;
if (!this.isNew) {
this.clienteService.get(this.clienteId).subscribe(c => {
this.cliente = c;
this.formNuevo.patchValue(this.cliente);
});
}
});
This is the client-service.ts
(get
):
public get(idClient: number): Observable<Client> {
return this.http.get<Client>(`${PREFIX}/${idClient}`);
}
This is the error of the new subscribe:
-> 'clienteId'
: object access via string literals is disallowed (no-string-literal)tslint(1)
-> subscribe
: subscribe is deprecated: Use an observer instead of a complete callback (deprecation)tslint(1)
How can I solve the problem and apply the changes to this subscribe?
Solution
-
Use higher order mapping operator like
switchMap
to map from one observable to another. Try to avoid nested subscriptions. -
The "error" is mostly caused by trying to send one or the other callbacks for subscription while specifying
null
for other ones. For eg. usingnext
andcomplete
withnull
forerror
. It could be solved by sending an observer object that explicitly specifies the callbacks.
Try the following
import { iif, NEVER } from 'rxjs';
import { switchMap } from 'rxjs/operators';
this.route.params.pipe(
switchMap(params => {
this.clienteId = +params['clienteId'];
this.isNew = !this.clienteId;
return iif( // <-- `iif` for conditional mapping
() => !this.isNew,
this.clienteService.get(this.clienteId),
NEVER // <-- don't emit if condition fails
);
})
).subscribe({
next: c => {
this.cliente = c;
this.formNuevo.patchValue(this.cliente);
},
error: error => {
// handle error
},
complete: () => {
console.log('Request complete');
}
});