【问题标题】:How to delete/update async way and when should I unsubscribe?如何删除/更新异步方式以及何时取消订阅?
【发布时间】:2020-01-11 10:14:38
【问题描述】:

我目前是 Angular 的新手。

异步管道的主要目标之一是自动为您处理订阅和取消订阅。

1. 在处理删除或更新(都是 API 服务)时,是否需要通过 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. 是否有另一种方法可以从 Observable 中删除特定元素,而无需再次调用刷新 projects$ 的 api?像这样的东西,而不是上面的那个:

    //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();
                }
            });
        }
    }
    

【问题讨论】:

    标签: angular rxjs


    【解决方案1】:

    这确实取决于您的要求,但您始终可以使用 async 管道,它将通过 subscribingunsubscribing 为您处理 observable 的生命周期

    -您可以使用一些 RxJS 运算符来为您处理 unsubscribe。喜欢take(1)first()of()from()

    -如你所说,取消订阅 NgDestroy

    另外,对于 Observable 来说,破坏不是一回事,你要么unsubscribecomplete 要么两者都

    在响应式编程中仅供参考,最好使用声明式方法

    等等,那是什么?

    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)
          );
    
      }
    

    你看到我做了什么吗?我删除了方法。

    然后在你的组件中你称之为testService.testObject$

    你看我做了什么,我摆脱了这个方法,原因如下:

    1. -利用 rxjs 可观察对象和操作者的强大功能
    2. -有效兼容的流
    3. -easy 分享 observables
    4. -随时响应用户操作

    【讨论】:

      猜你喜欢
      • 2021-10-17
      • 1970-01-01
      • 2020-03-09
      • 1970-01-01
      • 1970-01-01
      • 2019-04-21
      • 1970-01-01
      • 2019-07-19
      • 1970-01-01
      相关资源
      最近更新 更多