Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use one instance of a Service per Component

Using Angular 8 I have two components:

@Component({ selector: 'a' })
export class A_Component {
    constructor(dataService: DataService) { }
}

@Component({ selector: 'b' })
export class B_Component {
    constructor(dataService: DataService) { }
}

And the DataService is as follows:

export class DataService {
    public getValue(): Observable<number> { }
    public setValue(value: number) { }
}

Components A and B use DataService to communicate which their child (grandchild, ...) components.

But I want each Component, A and B, to have their own instance of DataService.

How to do this?

like image 605
Miguel Moura Avatar asked Oct 20 '25 12:10

Miguel Moura


1 Answers

Use in this way

@Component({ selector: 'a',
    providers: [DataService]
})
export class A_Component {
    constructor(dataService: DataService) { }
}

@Component({ selector: 'b',
    providers: [DataService]
})
export class B_Component {
    constructor(dataService: DataService) { }
}
like image 84
Ashot Aleqsanyan Avatar answered Oct 23 '25 00:10

Ashot Aleqsanyan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!