I have two entities: Organization
and User
. In my component, I have access to the currently authenticated user like this:
// component.ts
public authenticatedUser$ = this._authService.authenticatedUser$.pipe(
tap((user) => {
console.log('authenticatedUser$: ', user); // {id: '123', organizationId: '456',...}
}),
catchError((err) => {
return EMPTY;
})
);
What I am trying to do is get the organization that this user belongs to. I've been trying different variations of this without much success:
// component.ts
// private _organizationSubject:Subject<IOrganization>();
// public organization$ = this._organizationiSubject.asObservable();
public organization$ = this.authenticatedUser$.pipe(
map(
(user) =>
tap((user) => {
console.log('user', user);
})
// this._organizationService.getOrganization(user.organizationId)
// this._organizationSubject.next([--response from service--]);
),
catchError((err) => {
return EMPTY;
})
);
...
ngOnInit(): void {
// actual call(s) need to go here...
this.authenticatedUser$
.pipe(
tap((user) => console.log('user: ', user)),
tap((user) => {
this._organizationService.getOrganization(
user.organizationId
);
}),
catchError((err) => {
return EMPTY;
})
)
.subscribe();
}
I realize my ???map
is likely incorrect as well. I've been watching a lot of Deborah Kurata's videos & trying to make my data stream mimic her action streams. I am working with two data streams as I am always working with an authenticated user. There is no "interaction" to get these values.
In following her advice:
// what do we want (organization)
// what do we have (org id)
// when do we want it (when page loads e.g. OnInit)
Doing this a procedural way would be quite simple, however I'm really struggling with making it work in a declarative way.
EDIT
I have something working, but still struggling outside of just guessing what is happening.
// component.ts
public authenticatedUser$ = this._authService.authenticatedUser$.pipe(
catchError((err) => {
return EMPTY;
})
);
...
ngOnInit(): void {
this.authenticatedUser$
.pipe(
switchMap((user) =>
this._organizationService
.getOrganization(user.organizationId)
.pipe(tap((data) => console.log('data: ', data))) // {id: '123', name: 'My Org', ...}
),
catchError((err) => {
return EMPTY;
})
)
.subscribe();
}
Since I am using switchMap
will I also need to unsubscribe? Perhaps in the ngOnDestory
method or something?