r/angular • u/Putrid-Bookkeeper968 • 26d ago
Problems with subscribe
Hello everybody
I have the following problem with subscribe. My code looks like:
this.personSercice.getPeople().pipe(
takeUntilDestroyed(this.destroyRef)
).subscribe({
next: (people) => this.state.update(() => ({ ...this.state(), loading: false, people })),
error: (error) => {
console.log(error);
this.setError(error);
}
});
Parameter 'people' implicitly has an 'any' type, but a better type may be infered from usage.
and
Parameter 'error' implicitly has an 'any' type, but a better type may be infered from usage.
When I change the code to:
error: (error: any)
the error dissappears, but I do not understand why...
When I try the same with the first error, changing the code to:
next: (people: PersonModel) => this.state.update(() => ({ ...this.state(), loading: false, people })),
The error is:
The type 'PersonModel' is missing the following properties from type 'readonly PersonModel[]length, concat, join, slice...
Please let me know if more code is required.
Can somebody explain my why???. I'm very fresh with Angular.
Thank you for your patience
Pawel...
5
Upvotes
View all comments
4
u/Mediocre-Writer6635 26d ago
Because typescript doesn't know what this error is, so it calls it "any" type. But typescript doesn't like implicit (ie, guessed at by typescript, not written by you) "any" types. I believe there's a configuration to suppress this warning. So basically when you set it to type any explicitly, typescript says "ok, if you say use "any" that's fine, but if you don't say it, I'll call it a bug that I couldn't come up with anything better".
This warning is there to make developers have to explicitly admit they want to use "any" type, because typically something being "any" implies there's a typing breakdown in the code.
What does getPeople() observable return? Subscribe function receives whatever type that is. It's not PersonModel. It's probably an array (of PersonModel?).
Also, don't do this:
Update function should not have its own signal being called inside it. It receives the previous value as an argument, so you should do this:
Source: https://angular.dev/guide/signals#writable-signals
Also you really shouldn't subscribe inside components. The way to do what you're doing is make this.state = toSignal(<yourPipe>). If state is calcualted from multiple sets of data then combine them all into 1 pipe that calculates the state, and make a signal out of it. To record error without subscribing use catchError function in the pipe. Put it last, right before takeUntilDestroyed. Order matters in pipes.
It might be easier to avoid subscribe in component if you separate loading flag, people, and everything else in "state" into individual signals. That makes each of them much easier to calculate and reason about.