Created
October 8, 2020 04:26
-
-
Save vespertilian/7ad0a4817079817dc8c85663cf686417 to your computer and use it in GitHub Desktop.
Use an on destroy service provider instead of creating a subject and destroying it for every component
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Service | |
@Injectable() | |
export class OnDestroyService implements OnDestroy { | |
triggered$ = new Subject() | |
ngOnDestroy() { | |
this.triggered$.next() | |
this.triggered$.complete() | |
} | |
} | |
// Use in providers | |
@Component({ | |
selector: 'my-component', | |
templateUrl: './my.component.html', | |
styleUrls: ['./my.component.scss'], | |
providers: [ | |
OnDestroyService | |
] | |
}) | |
export class MyComponent implements OnInit { | |
constructor(private onDestroy: OnDestroyService, private fooService: FooService) { } | |
ngOnInit() { | |
fooService | |
.getData | |
.pipe(takeUntil(this.onDestroy.triggered$)) | |
.subscribe((v) => console.log(v)) | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment