0
votes

I'm currently a newbie with Angular.

One of the main goal of async pipe is automatically take care of subscribing and unsubscribing for you.

1. When dealing with delete or update (both are API services), Should 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();
            }
        });
    }
}
  1. Is there another way to delete a specific element from Observable without calling again the api that refreshs the projects$? Something like this, instead with the one above:

    //In this case this.projects type is not an 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

1 Answers

0
votes

it really depends on your requirement but you can always either use the async pipe which will handle the lifecycle of an observable for you by subscribing and unsubscribing

-You can use some of the RxJS operators that will handle the unsubscribe for you. Like take(1), first(), of(), from().

-Unsubscribe on the NgDestroy as you mention

Also, destroying is not a thing for Observable, you either unsubscribe, complete or both.

FYI in reactive programming is better to do the Declarative approach

wait, what is that?

testObject$ = this.http.get(url).pipe(
      map((resp: any) => 
           ({
            id: resp.data.id,
            view: resp.data.view,
            resourceName: resp.data.resourcename,
            loadCapacity: resp.data.loadcapacity
          }) as TestObject)
      );

  }

You see what I did? I erased the method.

then in your component you call it testService.testObject$

You see what I did I got rid of the method and here's why:

  1. -Leverage the power of rxjs observables and opeartors
  2. -effectively compatible streams
  3. -easy share observables
  4. -readily react to user action