Having recently started using Angular, I'm facing an issue with passing an array to a different component that is not parent or child related. What I aim to achieve is: upon selecting rows from the first component table, a new view should open up displaying the selected rows.
First component:
openExecutionDialog(): void {
....
dialogRef.afterClosed().subscribe((result) => {
if (result === true) {
this.dataService.invocationBulk(new HttpParams(), this.checkedIds).subscribe(
(changed) => {
var taskids = Array.from(this.checkedIds.values());
this.taskService.saveData(taskids)
},
(error) => {
..
}
});
}
taskService:
public tasksSubject = new BehaviorSubject<Task[]>([]);
data$ = this.tasksSubject.asObservable();
constructor(
private dataService: DataService)
{}
public saveData(taskids: number[]){
this.dataService.getTasks(taskids).subscribe((data) => {
this.retryTasks = data;
});
}
setTasks(tasks: Task[]) {
this.tasksSubject.next(tasks);
debugger
}
}
The definition of method getTasks is:
getTasks(taskId: number[]): Observable<RetryTaskResource[]> {
return this.apiDataService.getTasksUrl().pipe(
mergeMap((rootUrl) =>
this.http.get<Task[]>(`${rootUrl}${taskId}`)
),
map((result: Task[]) => {
return result;
})
);
}
Second Component
dataSource = new MatTableDataSource();
constructor(private taskService: TaskService) {
this.taskService.data$.subscribe(data => {
this.dataSource = data;})
}
HTML
<div class="table-container">
<table
mat-table
[dataSource]="dataSource"
matSort
matSortActive="zeitstempel"
matSortDisableClear
matSortDirection="desc"
>
<ng-container matColumnDef="modul">
<th mat-header-cell *matHeaderCellDef mat-sort-header disableClear>
Module
</th>
<td mat-cell *matCellDef="let row">{{ row.module }}</td>
</ng-container>
...
I've explored various approaches without success. Upon debugging, I can confirm that the tasks[] in the first component are populated.
2nd Approach from Angular pass array to another (NOT child) component
First Component
...
(changed) => {
var taskids = Array.from(this.checkedIds.values());
this.dataService.getTasks(taskids).subscribe((data) => {
this.markAsAccepted(data)
});
}
markAsAccepted(items: Task[]) {
this.taskService.addToAccepted(items);
}
taskService
private acceptedArray: RetryTaskResource[] = [];
public acceptedArraySubject = new BehaviorSubject<RetryTaskResource[]>[];
addToAccepted(items: RetryTaskResource[]) {
this.acceptedArray = items;
this.acceptedArraySubject.next(this.acceptedArray);
}
Second Component
acceptedArray: Observable<Task[]> | undefined;
constructor(....) {
this.dataService.acceptedArraySubject.pipe(share());
}