I am attempting to make my application more reactive/declarative vs procedural & having a really hard time trying to grasp not passing arguments to/from my service.
My url looks like this: /settings/organizations/26ee00d1-9fd8-4e38-a195-024c11ae0958
// organization.component.ts
organizationId: string;
...
constructor(private readonly activatedRoute: ActivatedRoute) {
//...
}
ngOnInit(): void {
this.organizationId = this.activatedRoute.snapshot.paramMap.get('organizationId')!;
this.fetchOrganization(this.organizationId);
}
...
fetchOrganization(organizationId: string): void {
this.organization$ = this.organizationService
.getOrganization(organizationId)
.pipe(
catchError((err) => {
console.log('err: ',err);
return EMPTY;
})
);
}
Here is what my service looks like:
// organization.service.ts
...
getOrganization(organizationId: string): Observable<Organization> {
return this.httpClient.get<Organization>(
`${this.baseURL}/v1/organizations/${organizationId}`
)
.pipe(catchError((err) => throwError(err)));
}
I've been pouring over this SO thread to think more reactive and not "pass" values around. I am slowly grasping that way of thinking, but I'm really struggling with how to get the organizationId
to my service in a declarative way.
For example, this is what my commponent.ts
file might look like:
organization$ = this.organizationService.organization$.pipe(
catchError((err) => {
this.handleError(err);
return EMPTY;
})
);
Then the service like this:
organization$ = this.httpClient
.get<Organization>(
`${this.baseURL}/v1/organizations/${organizationId}`
)
.pipe(catchError((err) => throwError(err)));
If I'm not "passing" the organizationId
to my service, how can I get the value of organizationId
? Does the routing logic live in the service now?
I've also tried without success trying to make organization$
in my service some sort of Subject or BehaviorSubject. I am just learning some of these techniques, and I understand the basics of Observable/Subjet/BehaviorSubjet etc. I'm really struggling how to get the id the "angular" way.
I think this GitHub code is very similar to what I am trying to accomplish. Specifically this part:
private productSelectedSubject = new BehaviorSubject<number>(0);
productSelectedAction$ = this.productSelectedSubject.asObservable();
//
private organizationSubject = new BehaviorSubject<string>('26ee00d1-9fd8-4e38-a195-024c11ae0958');
organizationId$ = this.organizationSubject.asObservable();
// where/how do I get the actual value of the url segment?
I am struggling how to pick up the url vs. an input change.
EDIT/UPDATE
I failed to mention what my template looks like. I am using the async
pipe to subscribe/un-subscribe to my organization$
variable.
<ng-container *ngIf="organization$ | async as organization; else loading">
<div>{{ organization.name}}</div>
</ng-container>
...
<ng-template #loading>
<div>Loading...</dv>
</ng-template>