在Angular 7中,如果注入的服务被取消设置,可能有以下几个解决方法:
import { Component } from '@angular/core';
import { MyService } from './my.service';
@Component({
selector: 'app-my-component',
template: '...'
})
export class MyComponent {
constructor(private myService: MyService) { }
}
import { NgModule } from '@angular/core';
import { MyService } from './my.service';
@NgModule({
providers: [MyService]
})
export class AppModule { }
OnDestroy
接口),请确保在组件销毁时取消该服务的订阅或清除资源。例如,在组件中的ngOnDestroy
方法中取消订阅:import { Component, OnDestroy } from '@angular/core';
import { MyService } from './my.service';
import { Subscription } from 'rxjs';
@Component({
selector: 'app-my-component',
template: '...'
})
export class MyComponent implements OnDestroy {
private subscription: Subscription;
constructor(private myService: MyService) {
this.subscription = this.myService.getData().subscribe(data => {
// 处理数据
});
}
ngOnDestroy() {
this.subscription.unsubscribe();
}
}
这些解决方法可能会帮助您解决“Angular 7注入的服务被取消设置”的问题。