0

I have service like folowing:

@Injectable({
  providedIn: 'root'
})
export class BoxContainerService {
    private boxBehaviour: BehaviorSubject<any[]> = new BehaviorSubject<any[]>([]);

    boxes$ = this.boxBehaviour.asObservable();

    addBox(b: any) {
            if (!b) return;

            this.boxBehaviour.next([...this.boxBehaviour.value, layer]);
    }
}

And I am injection in multiple components like following.

@Component({
  selector: 'my-list',
  templateUrl: './my-list.component.html'
})
export class MyListComponent implements OnInit, OnDestroy {

    constructor(private service: BoxContainerService) {     
    }

    ngonInit(){     
    }  
}

But I want to get new instance of BoxContainerService every route change. When I refresh the page, new instace is created. But if route from MyList_page to B_page and againg MyList_page, the boxes$ count is increasing. I want recreate the service instance during the module. Because I will import the module in another module.

1

2 Answers 2

1

You can remove the providedIn from your service's @Injectable

@Injectable({
})

And you can provide the service at component level as -

@Component({
  selector: 'my-list',
  templateUrl: './my-list.component.html',
  providers: [ BoxContainerService ]
})
export class MyListComponent implements OnInit, OnDestroy {

    constructor(private service: BoxContainerService) {     
    }

    ngonInit(){     
    }  
}

A new instance of BoxContainerService will be created, every time MyListComponent is created (in your case, when it is routed to)

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, I updated the post. Because I want to use module level dependency, I will import the module in another module. I am importing multiple components the service.
0

When you inject a service, it will be resolved by first provider it encounters going up the tree.

Right now, you probably registered you service on the module level.

You can make your list component (or some parent component, depending on what exactly you need to achieve) a provider for given service. This means that this component and all children components will resolve it to this instance - and an instance will be created for each instance of the component.

@Component({
  selector: 'my-list',
  templateUrl: './my-list.component.html',
  providers: [BoxContainerService]
})
export class MyListComponent implements OnInit, OnDestroy {

    constructor(private service: BoxContainerService) {     
    }

    ngonInit(){     
    }  
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.