I seem to be encountering a problem with the ReplaySubject
. I can't quite pinpoint what I've done wrong, but the issue is that whenever I make a change and save it in the backend, the ReplaySubject
fetches new data but fails to display it on the screen.
I attempted using detectChanges
without success. I understand that detectChanges
only functions within a parent-child relationship.
This issue occurs during updates https://i.sstatic.net/DHfRC.png
And this happens upon reloading the page https://i.sstatic.net/GoX0H.png
If I eliminate this.data.next(res)
from this line of the Put Request
, everything works. However, I have to refresh the page to see the updated data again.
return this.http.put(api, dataModel).subscribe(res => this.data.next(res));
Here's the code snippet for the service.
@Injectable({
providedIn: "root"
})
export class ModelDataService {
public baseUrl = environment.backend;
private data = new ReplaySubject<any>();
public userID = this.authService.userID;
constructor(private http: HttpClient, private authService: AuthService) {
}
public getJSON() {
return this.http.get(`${this.baseUrl}/data/${this.userID}`).subscribe(res => this.data.next(res));
}
public dataModel(): Observable<any> {
return this.data.asObservable();
}
public setData(data: Model) {
const api = `${this.baseUrl}/data`;
const user_id = this.authService.userID;
this.http.post(api, data, {
headers: {user_id}
}).subscribe(res => this.data.next(res));
}
public updateDate(id: string, dataModel: Model) {
const api = `${this.baseUrl}/data/${id}`;
return this.http.put(api, dataModel).subscribe(res => this.data.next(res));
}
}
Now moving onto the component.
public model$: Observable<Model>;
public model: Model;
constructor(
public authService: AuthService,
private modelDataService: ModelDataService,
public dialog: MatDialog,
public cd: ChangeDetectorRef) {
}
ngOnInit() {
this.authService.getUserProfile(this.userID).subscribe((res) => {
this.currentUser = res.msg;
});
this.modelDataService.getJSON();
this.model$ = this.modelDataService.dataModel();
this.model$.subscribe((data) => {
this.model = data; // here if i try to console log then I have the array but the page it will be blank
console.log(data);
});
}
As an example, I attempt to display data like so.
<ng-container class="Unit-unit-unitGroup" *ngFor="let personalData of model.personalData; let id = index">
</ng-container>
In the put
Request, when I added a console log, this is what I observed.
https://i.sstatic.net/vmfaG.png
However, upon reloading, it seems like the data structure changes. See imagehttps://i.sstatic.net/s2l2O.png