angular的service特性

239 阅读1分钟

一旦service在根模块注册(@Injectable({ providedIn: 'root' }))随应用程序一直存在,也是全局的

  • 产生的场景问题。
    • 当组件销毁,组件中有执行服务中的异步方法,不会随组件销毁自动销毁。所以需要特别注意。
    
    // dashboard.component.ts
    this.service.api().subscribe((retData: any) => {
        if (this.apiService.isEmpty(retData.resultList)) {
          this.modalSrv.confirm({
            nzTitle: '未设置默认系统',
            nzContent: `没有默认系统`,
            nzOkText: '立刻设置',
            nzCancelText: '稍后设置',
            nzOnOk: () => {
              ...
            },
          });
        }
    });
    // 假如因为重定向等原因导致接口还没相应完成就跳转到了别的页面,这弹窗提示可能出现在别的页面。
    

service使用事件订阅,主动发送消息

  • 防止订阅中心被重复注册。
    • 可能原因:1,组件销毁没有取消订阅;2,组件被多次实例化
    import { EventEmitter, Injectable } from '@angular/core';
    @Injectable({
      providedIn: 'root',
    })
    export class ProgressmodalService {
        public statusChanged: EventEmitter<any> = new EventEmitter();
        constructor(
            private notification: NzNotificationService,
            private _httpClient: _HttpClient,
        ) {}
        sendStatus(){
            setTimeout(()=>{
                this.statusChanged.next({code:'xxx',msg:'发布消息'});
            },5000)
        }
    }
    // conponent.ts
    import { Subscription } from 'rxjs';
    export class DomeComponent {
        private subscription: Subscription | undefined;
        constructor(){
            this.subscription = this.progressmodalService.statusChanged.subscribe(
                async (result) => {
                    // 还可以使用异步方法
                    const res = await api('/xxx')
                    console.log(res)
                    console.log(result)
                })
            )
            // 通过查看注册的数量,就知道是否又被重复订阅。然后在去定位为什么注册了多次
            console.log(this.progressmodalService.statusChanged)
        }
        ngOnDestroy() {
            this.subscription?.unsubscribe();
        }
    }
    

手动注册的服务是独立的,不会共享一个服务实列。该路由复用服务不会发生共享

```
import { Injector } from '@angular/core';
const injector = Injector.create({ 
    providers: [{ provide: RouteStrategyService, useClass: RouteStrategyService }] 
});
const routeStrategyService = injector.get(RouteStrategyService);
```

通过extends去继承服务,super初始化父服务的方法等。

// 父服务
import { Injectable } from '@angular/core';
@Injectable({ providedIn: 'root', })
export class BaseService { 
    constructor() { 
        console.log('BaseService initialized'); 
    } 
    baseMethod(): void { 
        console.log('This is a method from the BaseService'); 
    } 
}

// 子服务
import { Injectable } from '@angular/core';
import { BaseService } from './base.service';
@Injectable({ providedIn: 'root', }) 
export class ExtendedService extends BaseService { 
    constructor() { 
        super(); 
        console.log('ExtendedService initialized'); 
    } 
    extendedMethod(): void { 
        console.log('This is an additional method from the ExtendedService'); 
    } 
}