Issue
I have a method that calls an Observable service. I subscribe it and destroy it when navigate, but when I navigate back my method stack the results
Note: Angular CLI: Version 13.0.2 | npm 8.1.0
//home component
public workList:workModel[] = [];
serviceSubscription:Subscription;
constructor(
public workService: WorkServices
) {
this.serviceSubscription = this.getWorkList();
}
ngOnInit(): void {
//this.serviceSubscription = this.getWorkList();
}
ngOnDestroy(): void {
this.serviceSubscription.unsubscribe();
}
getWorkList(){
this.workList = [];
return this.workService.getWorks().subscribe((resp:Array<workModel>) => {
this.workList = resp.reverse();
console.log("work list ->", this.workList);
})
}
//**************************************************************
//service
@Injectable({
providedIn: 'root'
})
export class WorkServices {
private URL = "http://localhost:3000/work";
private works:workModel[];
constructor(
public http:HttpClient
){
this.works = new Array<workModel>();
}
getWorks(){
return this.http.get(this.URL).pipe(map((resp:any) => {
resp.forEach((w:workModel) => {
this.works.push(new workModel(
w.description,
w.client,
w.employees,
w.materials,
w.isFinished,
w.cost,
w.id
))
})
return this.works;
}));
}
/*
Console
work list -> Array [ {…}, {…} ] // load page
work list -> Array(4) [ {…}, {…}, {…}, {…} ] // Navigate and back first time
work list -> Array(6) [ {…}, {…}, {…}, {…}, {…}, {…} ] // Navigate and back second time
*/
Solution
Apparently the results are cached in your service, in the works
array. If this behavior is not desired, then you can simply remove the works
property from the service and remove the usage of it from the getWorks
method:
getWorks() {
return this.http.get(this.URL).pipe(
map((resp: any) => resp.map((w: workModel) =>
new workModel(
w.description,
w.client,
w.employees,
w.materials,
w.isFinished,
w.cost,
w.id
))
)
);
}
Answered By - Octavian Mărculescu
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.