I've integrated NGXS into my Angular project for state management, with updates being triggered by a WebSocket plugin associated with NGXS.
Here is the structure I have implemented:
model.ts
export interface Student {
id: string;
name: string;
passed: boolean;
}
student.action.ts
export class GetStudents{
...
}
export class UpdateStatus {
static readonly type = '[Student] Update Status';
constructor( studentId: string ) {}
}
student.state.ts
...
export class StudentStateModel {
students: Student[];
}
@State<StudentStateModel>({
name: 'student',
defaults: {
students: []
}
})
@Action(GetStudents)
...
@Action(UpdateStatus)
updateStatus(
{ getState, setState }: StateContext<StudentStateModel>,
{ studentId }: UpdateStatus
) {
const students = getState().students;
const index = students.findIndex((i) => i.id === studentId);
setState((state: ApprovalStateModel) => {
state.students[index].passed = true;
return state;
});
}
...
I have created 2 components (parent and child):
1/ The parent component maintains the list of students
students$: Observable<any>; // Get list of Students from Store GetStudents
students.component.html
<div *ngFor= "let student of students$ | async">
<app-student-detail
[student] = "student"
></app-student-detail>
</div>
2/ The child component displays the details of each student and includes an input
@Input() student: Student = null;
student-detail.component.html
<div *ngIf="student">
<p>Id: {{student.id}}</p>
<p>Name: {{student.name}}</p>
<p>Result: {{student.passed}} </p>
</div
I utilized the WebSocket plugin to update the student state by sending a message
{"type": "[Student] Update Status", "studentId" : "10001"}
Outcome:
While the log indicates that the state was successfully updated with passed = true for student id 10001, the UI does not reflect this change.
I suspect there may be an issue with my implementation, any suggestions or insights would be greatly appreciated.