Search code examples
javascriptangulartypescriptrxjsbehaviorsubject

Rxjs : prevent pushing data to subjects from outisde the service


Within my anguular app , i ve this service :

@Injectable()
export class myService{

  myBehaviouSubject= new BehaviorSubject("");


  setData(){
     this.myBehaviouSubject.next("123");
  }

}

Inside my app.component , i m able to get the value , but i want to keep it readonly or editable only inside the service itself , i want to prevent to push any data from component (.next('DATA'))

    @Component({

    })
    export class AppComponent implements OnInit {

      constructor(public myService : MyService) { }

    getData(){
      // GET VALUE
      this.myService.myBehaviouSubject.value
    }

    unwantedMethodToSetValue(){
           // SET VALUE -> i want to prevent this
           this.myService.myBehaviouSubject.next("unwanted value")

    }

}

Suggestions ?


Solution

  • You can keep the observable inside service only by declaring it as private field of a class.

    @Injectable()
    export class myService {
    
      private myBehaviouSubject = new BehaviorSubject("");
    
      // Use this observable inside the app component class.
      myBehaviouSubjectObservable = myBehaviouSubject.asObservable();
    
      setData() {
        this.myBehaviouSubject.next("123");
      }
    }
    
    @Component({
    
    })
    export class AppComponent implements OnInit {
    
      constructor(public myService: MyService) {}
    
      getData() {
        // You can subscribe to observable and can get value here
        this.myService.myBehaviouSubjectObservable.subscribe((value) => {
          console.log(value);
        })
      }
    
      unwantedMethodToSetValue() {
        // SET VALUE -> you cannot do this here now.
        this.myService.myBehaviouSubject.next("unwanted value")
    
      }
    
    }