I feel like I fundamentally misunderstand one part of Angular, imagine the following:
You have a navbar component which shows the logged in user, something like:
<nav *ngIf="user$ | async as user">user.name</nav>
then you have a user-edit component, something like:
<div *ngIf="user$ | async as user" class="form">
<input [(ngModel)]="user.name">
</div>
where user$
is an Observable
that one gets from a service.
Now in the app you naturally show a navbar and the other components, this means both components need the same data. To prevent multiple api calls you can use an cachedResponse
or use shareReplay()
within a user.service.ts
. Great!
Here's my question, making the service this way requires a lot more code than, for instance, sharing a user
object directly from a service
like so:
export class UserService implements OnInit {
public user: User = new User;
constructor(public http: HttpClient) {}
ngOnInit() {
this.http.get<User>('api.com/user').subscribe((user: User) => this.user = user);
}
updateUser() {
this.http.post('api.com/user', this.user).subscribe((user: User) => this.user = user);
}
}
And in both components just add:
constructor(public userService: UserService) {}
and use it in the template like so:
<nav>userService.user.name</nav>
and:
<div class="form">
<input [(ngModel)]="userService.user.name">
<button (click)="userService.updateUser"></button>
</div>
Apart from not using the Angular Async Pipe what would be bad about a structure like this?
If you update the name all other components also get updated.
I saw this question on here but the all the answers are non-issues (it seems to me). Just to answer them:
- Memory leak, no because http services unsubscribe in Angular (I would only use this for http calls).
- Value update is not track, this could be an issue if you want to mutate values from the same observable but if you would want that one would make a different observable.
- Separation of concerns, what is bad about having one global user object? Only components which use the
UserService
have access. - Not really an issue with this type of architecture.
Why would this be bad?, or rather why don't I see any examples of people doing this.