When dealing with delete/update, should I unsubscribe in Async Pipe mode?

Asked

Viewed 24 times

0

I’m new to Angular.

One of the main goals of async pipe is to automatically take care of signing up (subscribe) and unsubscribe (unsubscribe).

I have two doubts:

First Doubt

When dealing with delete or update (both are API services), I need to unsubscribe via ngOnDestroy?

projects$: Observable<Project[]>;

constructor(
    private projectService: ProjectService,
) { }

ngOnInit() {
    this.loadProject();
}   


loadProject(){
    this.projects$ = this.projectService.getProjects()
    .pipe(
        map(result => {
            if(result.success){
                return result.data;
            }
        })
    );
}


deleteProject(){
    if(this.projectToDelete){
        const id = this.projectToDelete.id;
        this.projectService.deleteProject(id).subscribe(result => {
            if(result.success){
                this.loadProject();
            }
        });
    }
}

Second Doubt

There is another way to delete a specific element of a Observable without calling the API that loads the projects$? Something below, different with the top code:

    //Neste caso  this.projectsects type não é um observable.
    deleteProject(){
        if(this.projectToDelete){
            const id = this.projectToDelete.id;
            this.projectService.deleteProject(id)
            .subscribe(result => {
                if(result.success){
                    this.projects = this.projects.filter(item => {
                        return item.id != id;
                    });
                    this.projectToDelete = null;
                    this.closeModal();
                }
            });
        }
    }

1 answer

0

Of documentation angular:

"The async pipe subscribes to an Observable or Promise and Returns the Latest value it has Emitted. When a new value is Emitted, the async pipe Marks the Component to be checked for changes. When the Component gets destroyed, the async pipe unsubscribes Automatically to avoid potential memory Leaks."

Async Pipe will do so much subscribe like the unsubscribe automatically when the component is started and destroyed

You must filter the array within the function map to change the value of a Observable:

this.projects$ = this.projects$.map(
    project => project.filter(
        item => item.id != id
    )
);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.