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.

barteloma
  • 6,403
  • 14
  • 79
  • 173
  • There are a lot of examples of Angular's DI here https://angular.io/guide/hierarchical-dependency-injection. Service can scoped Globally (Singleton), or by Module or Component. – Timothy Jun 08 '20 at 11:26

2 Answers2

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)

Vimal Munjani
  • 280
  • 1
  • 8
  • 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. – barteloma Jun 08 '20 at 11:33
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(){     
    }  
}
TotallyNewb
  • 3,884
  • 1
  • 11
  • 16