When we're looking to share data between routes, the only viable solution seems to use a service. Since we want data to be rerendered in the view when they are updated, we must use BehaviorSubject
.
So, correct me if i'm wrong but a simple component will look like this:
@Component({
selector: 'user-info',
template: `
{{($user | async).firstName}}
<button (click)="updateName()"></button>
`
})
export class UserInfoComponent {
private $user;
private subscribe;
constructor(private service: UserService) {
this.user$ = this.service.get();
}
updateName() {
this.subscribe = this.service.get().subscribe(user =>
this.service.update({...user, firstName: 'new-name'})
);
}
ngOnDestroy() {
this.subscribe.unsubscribe();
}
}
This sounds really frustrating because if we did not use the router we could just call the component with <user-info [user]="user | async"></user-info>
and it would be so much cleaner:
@Component({
selector: 'user-info',
template: `
{{user.lastName}}
<button (click)="updateName()"></button>
`
})
export class UserInfo2Component {
@Input() user: User;
constructor(private service: UserService) {}
updateName() {
this.service.update({...user, lastName: 'new-name'});
}
}
So my question is: Why is it so difficult to share data between routes ? Is there a better solution that I could have missed ?