The NGRX + Resolver issue arises when the component loads before the action is fully dispatched, causing interaction problems

I'm currently facing an issue with fetching data from a route and loading it into my state before displaying my detail component. To tackle this, I've implemented a resolver. Although my get request seems to be functioning, it appears that the API call is happening post component load.

@Injectable()
export class WorkOrderDetailResolver implements Resolve<WorkOrder> {

constructor(
private store: Store<fromApp.AppState>
) { }

waitForWorkOrderDataToLoad(route, state) {
this.store.dispatch(new WorkOrderActions.FetchWorkOrderFromAPIByID(+route.params['id']));
return this.store.select(state => state.workOrder.workOrderDetails).pipe(take(1));
}

resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<WorkOrder> | Promise<WorkOrder> | WorkOrder {
return this.waitForWorkOrderDataToLoad(route, state);
}
}

Here are the routes where I've clearly integrated the resolver into the WorkOrderDetailsComponent

 const workOrderRoutes: Routes = [
{ 
path: 'workorders', 
component: WorkOrderComponent,
children: [
{ path: 'new', component: WorkOrderEditComponent },
{ path: 'list', component: WorkOrderListComponent },
{ path: ':id', component: WorkOrderDetailComponent, resolve: { workOrderDetails: WorkOrderDetailResolver } },
{ path: ':id/edit', component: WorkOrderEditComponent }
]
}
];

Lastly, here's the code for the WorkOrdersDetailComponent:

@Component({
selector: 'app-work-order-detail',
templateUrl: './work-order-detail.component.html',
styleUrls: ['./work-order-detail.component.css']
})
export class WorkOrderDetailComponent implements OnInit {
private id: number; 
workOrder: WorkOrder;
workOrderState: Observable<{workOrders: WorkOrder[]}>;

constructor(private route: ActivatedRoute,
          private router: Router,
        ) { }

ngOnInit() {
console.log(this.route.snapshot.data);
this.workOrder = this.route.snapshot.data.workOrderDetails;
}

onEditWorkOrder() {
this.router.navigate(['edit'], {relativeTo: this.route});
}

}

To clarify the objective of the resolver code: It dispatches an action to fetch a workOrder by id from the API, stores it in the state (which works), and only then returns an observable of the workOrder stored in the state to load the WorkOrderDetailComponent.

The issue arises where the view cannot read the value of null for the workOrder the first time the route loads. However, upon navigating away and back to the page, the workOrder is no longer null. It seems like the resolver might not be functioning before the component loads. My intention is for the resolver to return Observable<{WorkOrder]> so that I can asynchronously load it in the view.

This could potentially be due to my misuse of rxjs operators for observables. I'm struggling to understand how observables function and how these operators should be properly chained. If that's the case, I would appreciate any insights on what's incorrect and why.

Thank you!

Answer №1

Ensure to wait for the selector to provide a value

this.store.pipe(
  select(state => state.workOrder.workOrderDetails),
  filter(details => !!details),
  take(1)
);

It's important to note that I'm utilizing the select operator instead of the select method directly on the store. The latter method is now deprecated and will be phased out in future updates.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Rendering HTML content in a preformatted <code> tag using Electron

Recently, a brand new electron/angular application was built with the code snippet running in main.ts: win.loadURL(url.format({ pathname: path.join(__dirname, 'dist/index.html'), protocol: 'file:', slashes: true })); After launc ...

Printing content from an Angular dashboard can be achieved by following a few

Currently, I am working on developing a legal document automation program for my company. However, I have encountered an issue during the final stages of completing this web application. For the layout and setup, I am using the default angular Dashboard l ...

Is there a syntax available for type annotation of arrays created from pre-declared variables?

According to my standards, all possible annotations are required in TypeScript. Therefore, TypeScript-ESLint is prompting me to annotate the `[ responseData, cognitoUser ]`. However, when I try to use the syntax `[ responseData1: ResponseData1, responseD ...

What is the best way to handle sending a single request after clearing multiple fields?

I have been using reactive forms and encountered an issue where resetting 5 specific fields triggers multiple requests instead of just one. I intend to send only one request after all changes, but currently, each field reset results in a separate request. ...

What is the reason that the values in the select option only appear once it has been clicked on?

After loading or reloading the page, I am experiencing an issue where the select options do not appear on the first click and the values are not displayed until the second click. Any assistance would be greatly appreciated! I am still new to coding, so ple ...

Ensuring TypeScript recognizes a class property as definitively initialized when set using a Promise constructor

I have a simple class definition that is giving me an error in TypeScript. class Container { resolveData: (s: string) => void // not definitely initialized error! data: Promise<string> constructor() { this.data = new Promise&l ...

Issues encountered with sending post requests to a yii2 application when using Angular4

After implementing the following code: this.http.post('http://l.example/angular/create/', {name: 'test'}).subscribe( (response) => console.log(response), (error) => console.log(error) ); I encountered an error on ...

Error message: Cypress Vue component test fails due to the inability to import the Ref type (export named 'Ref' is missing)

Recently, I created a Cypress component test for my Vue component by mounting it and verifying its existence. The component utilizes Vue's Ref type and is structured as a TypeScript component. However, during the test execution, Cypress encountered a ...

Issue with Angular/Chrome: The filter pipe is not able to be located

Even though this topic has been covered before, I have not found any satisfactory solutions. Here is my approach: play.module.ts import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; impor ...

Display content based on selected option

I am struggling to display a div based on the selection I make. Unfortunately, it's not working as expected. Can anyone offer guidance on how to tackle this issue? <div class ="row"> <div class="form-group col-md-6"> <label for= ...

Running cypress tests with regression or smoke tags within nx workspace is a straightforward process

I have a cypress project set up and I am trying to run cypress tests based on tags using the nx command. cypress grep--->"@cypress/grep": "^4.0.1" After applying the nx command like this: nx run e2e:e2e --tags=@regression The issu ...

Issue: The method spyOn cannot be used on the fromEvent function because it is either not writable or does not have a setter defined

After transitioning our codebase from rxjs v5.5.12 to rxjs v6.4.0, we encountered an error when running a test case. Old Code: import * as ObservableEvents from 'rxjs/Observable/fromEvent'; spyOn(ObservableEvents, 'fromEvent').and.ret ...

How can I use Angular 4 typescript to deactivate a button based on the value of a boolean variable?

I am looking to define a function in TypeScript called 'isActive()', which I will then invoke on a button within my HTML file. Additionally, I have already declared a boolean variable named 'isActive'. In this scenario, I have two butto ...

Trouble incorporating SCSS color variables into Angular component_IMPORT issue

My Angular 9 app has a folder structure that includes: | app | app.component.ts | app.component.html | app.component.scss | assets | _colors.scss The _colors.scss file contains definitions for two colors: $red: #DA0000; $blue: #1080E1; In the a ...

What steps can I take to stop a browser from triggering a ContextMenu event when a user performs a prolonged touch

While touch events are supported by browsers and may trigger mouse events, in certain industrial settings, it is preferred to handle all touch events as click events. Is there a way to globally disable context menu events generated by the browser? Alternat ...

How can Angular be used to create core styles in a CSS file rather than adding them dynamically within style tags?

Whenever I import a component, like MatTabsModule, it automatically generates styles within the head section: <style>.mdc-tab{min-width:90px;padding-right:24px....</style> I'd prefer to have all these styles generated in an external CSS f ...

The matInput value remains stagnant and fails to update

I am encountering an issue with a form Input field for username and password. Here is the code snippet: <mat-form-field class="mdb-form-field-modal form-adjustments"> <input (keydown)="emailBtnFocus($event)" tabindex="0" matInput placeholder ...

Broaden the current category within the MUI Theme

I am attempting to enhance the current options within MUI's theme palette by adding a couple of properties. Take a look at this example: declare module @material-ui/core/styles/createMuiTheme { interface CustomOptions extends SimplePaletteColorOptio ...

Encountered an error while setting up Angular 2 Server with Express: ERR

My website was built with Angular2 on the frontend and Node/Express on the backend. The frontend runs on port 4200 (run npm build to start it) while the backend runs on port 4201 (npm start). I have a user login management view that works perfectly on loc ...

The required dependencies for @angular/[email protected] and @angular/[email protected] have not been fulfilled

Details: npm version: 3.10.10 and nodejs version: 6.11.1 I am in the process of setting up a .NET project with an angular web API but am encountering unmet dependencies: "unmet peer dependency @angular/[email protected] and @angular/[email prote ...