user9876776
user9876776

Reputation:

Data share with service between unrelated components is not working

I have built a shared data service which should send dropdown choice from 1 component to the component which is its sibling's grandchild. but I cant get it to work.

Shared service:

@Injectable()
export class LiveDataService {
    private subject: BehaviorSubject<MyData> = new BehaviorSubject<MyData>(null);

    public currentValue(): MyData {
        return this.subject.value;
    }

    public changeValue(data: MyData): void {
        this.subject.next(data);
    }

    public getValue(): Observable<MyData> {
        return this.subject.asObservable();
    }
}

Sending Component

@Component({
})
export class MainComponent {
    constructor(private liveDataService: LiveDataService) {}

    onDropdownChange() {
        this.liveDataService.changeValue({id: event.value} as MyData);
    }
}

Receiving Component

@Component({
})
export class AnotherComponent implements OnInit {

    constructor(private liveDataService: LiveDataService) {}

    ngOnInit() {
        this.liveCutoffData.getValue().subscribe((myData) => {
            this.myData = myData;
            this.doSomething(this.myData);
       });
    }
}

my.module.ts

@NgModule({
    declarations: [
        MainComponent,
        AnotherComponent,
    ],
    imports: [
        ...
    ],
    providers: [
        LiveDataService,
    ],
  })
export class MyModule {
}

From logs I can see that MainComponent is sending changes. However AnotherComponent is not recieving those changes and nothing is happening

Upvotes: 0

Views: 57

Answers (1)

Igor
Igor

Reputation: 62213

Change @Injectable() to @Injectable({ providedIn: 'root'}) on the service which ensures it will be registered as a singleton service with angular.

@Injectable({providedIn: 'root'})
export class LiveDataService {
  // ...

See also Providing a singleton service

Upvotes: 1

Related Questions