When trying to exchange data between routes, the most effective method appears to be using a service. To ensure that data is updated and re-rendered in the view, we are required to utilize BehaviorSubject
.
Based on my understanding, a simple component would look something 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 process may seem cumbersome because if router wasn't involved, we could simply call the component with
<user-info [user]="user | async"></user-info>
, making it 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'});
}
}
Therefore, my question remains: Why is sharing data between routes so challenging? Is there possibly a more efficient solution that I have overlooked?