From 809b3c3d53517d79b94d455825a3fc54a0f0db7f Mon Sep 17 00:00:00 2001 From: Enea Jahollari Date: Sat, 16 Sep 2023 21:43:19 +0200 Subject: [PATCH] docs: connect fn (#58) --- docs/src/content/docs/utilities/connect.md | 48 +++++++++++++++++++++- 1 file changed, 46 insertions(+), 2 deletions(-) diff --git a/docs/src/content/docs/utilities/connect.md b/docs/src/content/docs/utilities/connect.md index 63d95ce7..969bbc0f 100644 --- a/docs/src/content/docs/utilities/connect.md +++ b/docs/src/content/docs/utilities/connect.md @@ -3,6 +3,50 @@ title: connect description: ngxtension/connect --- -WIP +`connect` is a utility function that connects a signal to an observable and returns a subscription. The subscription is automatically unsubscribed when the component is destroyed. If it's not called in an injection context, it must be called with an injector or DestroyRef. -Link to [connect](https://github.com/nartc/ngxtension-platform/blob/main/libs/ngxtension/connect/src/connect.ts) source code. +```ts +import { connect } from '@ngxtension/connect'; +``` + +## Usage + +It can be helpful when you want to have a writable signal, but you want to set its value based on an observable. + +For example, you might want to have a signal that represents the current page number, but you want to set its value based on an observable that represents the current page number from a data service. + +```ts +@Component() +export class AppComponent implements OnDestroy { + private dataService = inject(DataService); + + pageNumber = signal(1); + + constructor() { + connect(this.pageNumber, this.dataService.pageNumber$); + } +} +``` + +You can also use it not in an injection context, but you must provide an injector or DestroyRef. + +```ts +@Component() +export class AppComponent implements OnDestroy { + private dataService = inject(DataService); + + private injector = inject(Injector); + // or + private destroyRef = inject(DestroyRef); + + pageNumber = signal(1); + + ngOninit() { + connect(this.pageNumber, this.dataService.pageNumber$, this.injector); + + // or + + connect(this.pageNumber, this.dataService.pageNumber$, this.destroyRef); + } +} +```